📜  检查二叉树是否是单值的

📅  最后修改于: 2022-05-13 01:57:13.880000             🧑  作者: Mango

检查二叉树是否是单值的

给定一棵二叉树,任务是检查二叉树是否是单值的。如果发现是真的,则打印“YES” 。否则,打印“NO”

例子:

基于DFS的方法:想法是使用 DFS 遍历树并检查二叉树的每个节点是否与二叉树的根节点具有相同的值。如果发现是真的,则打印“YES” 。否则,打印“NO”

下面是上述方法的实现:

C++
1
                  /  \
                 1    1 
                / \    \
               1   1    1


Java
9
                 /  \
                2   4 
               / \   \
             -1   3   0


Python3
// C++ Program for the above approach
 
#include 
using namespace std;
 
// Structure of a tree node
struct Node {
    int data;
    Node* left;
    Node* right;
};
 
// Function to insert a new node
// in a binary tree
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Function to check If the tree
// is uni-valued or not
bool isUnivalTree(Node* root)
{
 
    // If tree is an empty tree
    if (!root) {
        return true;
    }
 
    // If all the nodes on the left subtree
    // have not value equal to root node
    if (root->left != NULL
        && root->data != root->left->data)
        return false;
 
    // If all the nodes on the left subtree
    // have not value equal to root node
    if (root->right != NULL
        && root->data != root->right->data)
        return false;
 
    // Recurse on left and right subtree
    return isUnivalTree(root->left)
           && isUnivalTree(root->right);
}
 
// Driver Code
int main()
{
 
    /*
                1
              /   \
             1     1
           /  \     \
          1    1     1
    */
    Node* root = newNode(1);
    root->left = newNode(1);
    root->right = newNode(1);
    root->left->left = newNode(1);
    root->left->right = newNode(1);
    root->right->right = newNode(1);
 
    if (isUnivalTree(root) == 1) {
 
        cout << "YES";
    }
    else {
 
        cout << "NO";
    }
    return 0;
}


C#
// Java Program for the above approach
import java.util.*;
class GFG
{
 
// Structure of a tree node
static class Node
{
    int data;
    Node left;
    Node right;
};
 
// Function to insert a new node
// in a binary tree
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return (temp);
}
 
// Function to check If the tree
// is uni-valued or not
static boolean isUnivalTree(Node root)
{
 
    // If tree is an empty tree
    if (root == null)
    {
        return true;
    }
 
    // If all the nodes on the left subtree
    // have not value equal to root node
    if (root.left != null
        && root.data != root.left.data)
        return false;
 
    // If all the nodes on the left subtree
    // have not value equal to root node
    if (root.right != null
        && root.data != root.right.data)
        return false;
 
    // Recurse on left and right subtree
    return isUnivalTree(root.left)
           && isUnivalTree(root.right);
}
 
// Driver Code
public static void main(String[] args)
{
 
    /*
                1
              /   \
             1     1
           /  \     \
          1    1     1
    */
    Node root = newNode(1);
    root.left = newNode(1);
    root.right = newNode(1);
    root.left.left = newNode(1);
    root.left.right = newNode(1);
    root.right.right = newNode(1);
 
    if (isUnivalTree(root))
    {
        System.out.print("YES");
    }
    else
    {
        System.out.print("NO");
    }
}
}
 
// This code is contributed by 29AjayKumar


Javascript
# python3 Program for the above approach
 
# Structure of a tree node
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
 
# Function to check If the tree
# is uni-valued or not
def isUnivalTree(root):
 
    # If tree is an empty tree
    if (not root):
        return True
 
    # If all the nodes on the left subtree
    # have not value equal to root node
    if (root.left != None and root.data != root.left.data):
        return False
 
    # If all the nodes on the left subtree
    # have not value equal to root node
    if (root.right != None and root.data != root.right.data):
        return False
 
    # Recurse on left and right subtree
    return isUnivalTree(root.left) and isUnivalTree(root.right)
 
# Driver Code
if __name__ == '__main__':
 
    # /*
    #             1
    #           /   \
    #          1     1
    #        /  \     \
    #       1    1     1
    # */
    root = Node(1)
    root.left = Node(1)
    root.right = Node(1)
    root.left.left = Node(1)
    root.left.right = Node(1)
    root.right.right = Node(1)
 
    if (isUnivalTree(root) == 1):
        print("YES")
    else:
        print("NO")
 
        # This code is contribute by mohit kumar 29


C++
// C# Program for the above approach
using System;
class GFG
{
 
// Structure of a tree node
class Node
{
    public int data;
    public Node left;
    public Node right;
};
 
// Function to insert a new node
// in a binary tree
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return (temp);
}
 
// Function to check If the tree
// is uni-valued or not
static bool isUnivalTree(Node root)
{
 
    // If tree is an empty tree
    if (root == null)
    {
        return true;
    }
 
    // If all the nodes on the left subtree
    // have not value equal to root node
    if (root.left != null
        && root.data != root.left.data)
        return false;
 
    // If all the nodes on the left subtree
    // have not value equal to root node
    if (root.right != null
        && root.data != root.right.data)
        return false;
 
    // Recurse on left and right subtree
    return isUnivalTree(root.left)
           && isUnivalTree(root.right);
}
 
// Driver Code
public static void Main(String[] args)
{
 
    /*
                1
              /   \
             1     1
           /  \     \
          1    1     1
    */
    Node root = newNode(1);
    root.left = newNode(1);
    root.right = newNode(1);
    root.left.left = newNode(1);
    root.left.right = newNode(1);
    root.right.right = newNode(1);
 
    if (isUnivalTree(root))
    {
        Console.Write("YES");
    }
    else
    {
        Console.Write("NO");
    }
}
}
 
// This code is contributed by 29AjayKumar


Java


Python3
// C++ program for the above approach
 
#include 
using namespace std;
 
// Structure of a tree node
struct Node {
    int data;
    Node* left;
    Node* right;
};
 
// Function to insert a new node
// in a binary tree
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Function to check If the tree
// is univalued or not
bool isUnivalTree(Node* root)
{
 
    // If tree is an empty tree
    if (!root) {
        return true;
    }
 
    // Store nodes at each level
    // of the tree
    queue q;
 
    // Insert root node
    q.push(root);
 
    // Stores value of root node
    int rootVal = root->data;
 
    // Traverse the tree using BFS
    while (!q.empty()) {
 
        // Stores front element
        // of the queue
        Node* currRoot = q.front();
 
        // If value of  traversed node
        // not equal to value of root node
        if (currRoot->data != rootVal) {
            return false;
        }
 
        // If left subtree is not NULL
        if (currRoot->left) {
 
            // Insert left subtree
            q.push(currRoot->left);
        }
 
        // If right subtree is not NULL
        if (currRoot->right) {
 
            // Insert right subtree
            q.push(currRoot->right);
        }
 
        // Remove front element
        // of the queue
        q.pop();
    }
 
    return true;
}
 
// Driver Code
int main()
{
 
    /*
                1
              /   \
             1     1
           /  \     \
          1    1     1
    */
    Node* root = newNode(1);
    root->left = newNode(1);
    root->right = newNode(1);
    root->left->left = newNode(1);
    root->left->right = newNode(1);
    root->right->right = newNode(1);
 
    if (isUnivalTree(root) == 1) {
 
        cout << "YES";
    }
    else {
 
        cout << "NO";
    }
 
    return 0;
}


C#
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Structure of a tree node
    static class Node {
        int data;
        Node left;
        Node right;
    };
 
    // Function to insert a new node
    // in a binary tree
    static Node newNode(int data)
    {
        Node temp = new Node();
        temp.data = data;
        temp.left = temp.right = null;
        return (temp);
    }
 
    // Function to check If the tree
    // is univalued or not
    static boolean isUnivalTree(Node root)
    {
 
        // If tree is an empty tree
        if (root == null) {
            return true;
        }
 
        // Store nodes at each level
        // of the tree
        Queue q = new LinkedList<>();
 
        // Insert root node
        q.add(root);
 
        // Stores value of root node
        int rootVal = root.data;
 
        // Traverse the tree using BFS
        while (!q.isEmpty()) {
 
            // Stores front element
            // of the queue
            Node currRoot = q.peek();
 
            // If value of  traversed node
            // not equal to value of root node
            if (currRoot.data != rootVal) {
                return false;
            }
 
            // If left subtree is not NULL
            if (currRoot.left != null) {
 
                // Insert left subtree
                q.add(currRoot.left);
            }
 
            // If right subtree is not NULL
            if (currRoot.right != null) {
 
                // Insert right subtree
                q.add(currRoot.right);
            }
 
            // Remove front element
            // of the queue
            q.remove();
        }
 
        return true;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /*
                    1
                  /   \
                 1     1
               /  \     \
              1    1     1
        */
        Node root = newNode(1);
        root.left = newNode(1);
        root.right = newNode(1);
        root.left.left = newNode(1);
        root.left.right = newNode(1);
        root.right.right = newNode(1);
 
        if (isUnivalTree(root)) {
            System.out.print("YES");
        }
        else {
            System.out.print("NO");
        }
    }
}
 
// This code is contributed by Dharanendra L V.


Javascript
# Python program for the above approach
 
# Structure of a tree node
class node:
     
    # Function to insert a new node
    # in a binary tree
    def __init__(self, x):
        
        self.data = x
        self.left = None
        self.right = None
 
# Function to check If the tree
# is univalued or not
def isUnivalTree(root):
     
    # If tree is an empty tree
    if(root == None):
        return True
     
    # Store nodes at each level
    # of the tree
    q = []
     
    # Insert root node
    q.append(root)
     
    # Stores value of root node
    rootVal = root.data
     
    # Traverse the tree using BFS
    while(len(q) != 0):
         
        # Stores front element
        # of the queue
        currRoot = q[0]
         
        # If value of  traversed node
        # not equal to value of root node
        if (currRoot.data != rootVal):
            return False
         
        # If left subtree is not NULL
        if (currRoot.left != None):
             
            # Insert left subtree
            q.append(currRoot.left)
         
        # If right subtree is not NULL
        if(currRoot.right != None):
             
            # Insert right subtree
            q.append(currRoot.right)
         
        # Remove front element
        # of the queue
        q.pop(0)
     
    return True
 
# Driver Code
if __name__ == '__main__':
     
    #
    #                1
    #              /   \
    #             1     1
    #           /  \     \
    #          1    1     1
         
    root=node(1)
    root.left= node(1)
    root.right = node(1)
    root.left.left = node(1)
    root.left.right = node(1)
    root.right.right = node(1)
     
    if(isUnivalTree(root)):
        print("YES")
    else:
        print("NO")
 
# This code is contributed by avanitrachhadiya2155


输出:
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Structure of a tree node
  class Node
  {
    public int data;
    public Node left;
    public Node right;
  };
 
  // Function to insert a new node
  // in a binary tree
  static Node newNode(int data)
  {
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return (temp);
  }
 
  // Function to check If the tree
  // is univalued or not
  static bool isUnivalTree(Node root)
  {
 
    // If tree is an empty tree
    if (root == null)
    {
      return true;
    }
 
    // Store nodes at each level
    // of the tree
    Queue q = new Queue();
 
    // Insert root node
    q.Enqueue(root);
 
    // Stores value of root node
    int rootVal = root.data;
 
    // Traverse the tree using BFS
    while (q.Count != 0)
    {
 
      // Stores front element
      // of the queue
      Node currRoot = q.Peek();
 
      // If value of  traversed node
      // not equal to value of root node
      if (currRoot.data != rootVal)
      {
        return false;
      }
 
      // If left subtree is not NULL
      if (currRoot.left != null)
      {
 
        // Insert left subtree
        q.Enqueue(currRoot.left);
      }
 
      // If right subtree is not NULL
      if (currRoot.right != null)
      {
 
        // Insert right subtree
        q.Enqueue(currRoot.right);
      }
 
      // Remove front element
      // of the queue
      q.Dequeue();
    }
 
    return true;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
 
    /*
                    1
                  /   \
                 1     1
               /  \     \
              1    1     1
        */
    Node root = newNode(1);
    root.left = newNode(1);
    root.right = newNode(1);
    root.left.left = newNode(1);
    root.left.right = newNode(1);
    root.right.right = newNode(1);
 
    if (isUnivalTree(root))
    {
      Console.Write("YES");
    }
    else
    {
      Console.Write("NO");
    }
  }
}
 
// This code is contributed by 29AjayKumar

时间复杂度: O(N)
辅助空间: O(1)

基于BFS的方法:想法是使用 BFS 遍历树并检查二叉树的每个节点是否具有等于二叉树的根节点的值。如果发现是真的,则打印“YES” 。否则,打印“NO” 。请按照以下步骤解决问题:

  • 使用 BFS 初始化一个队列以遍历二叉树。
  • 将二叉树的根节点插入队列。
  • 将树的左子树插入队列并检查队列前元素的值是否等于树的当前遍历节点的值。如果发现是假的,则打印“NO”
  • 将树的右子树插入队列并检查队列前元素的值是否等于树的当前遍历节点的值。如果发现是假的,则打印“NO”
  • 否则,如果遍历了树的所有节点,并且每个节点的值都等于根节点的值,则打印“YES”

下面是上述方法的实现:

C++

Java

YES

蟒蛇3

// C++ program for the above approach
 
#include 
using namespace std;
 
// Structure of a tree node
struct Node {
    int data;
    Node* left;
    Node* right;
};
 
// Function to insert a new node
// in a binary tree
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Function to check If the tree
// is univalued or not
bool isUnivalTree(Node* root)
{
 
    // If tree is an empty tree
    if (!root) {
        return true;
    }
 
    // Store nodes at each level
    // of the tree
    queue q;
 
    // Insert root node
    q.push(root);
 
    // Stores value of root node
    int rootVal = root->data;
 
    // Traverse the tree using BFS
    while (!q.empty()) {
 
        // Stores front element
        // of the queue
        Node* currRoot = q.front();
 
        // If value of  traversed node
        // not equal to value of root node
        if (currRoot->data != rootVal) {
            return false;
        }
 
        // If left subtree is not NULL
        if (currRoot->left) {
 
            // Insert left subtree
            q.push(currRoot->left);
        }
 
        // If right subtree is not NULL
        if (currRoot->right) {
 
            // Insert right subtree
            q.push(currRoot->right);
        }
 
        // Remove front element
        // of the queue
        q.pop();
    }
 
    return true;
}
 
// Driver Code
int main()
{
 
    /*
                1
              /   \
             1     1
           /  \     \
          1    1     1
    */
    Node* root = newNode(1);
    root->left = newNode(1);
    root->right = newNode(1);
    root->left->left = newNode(1);
    root->left->right = newNode(1);
    root->right->right = newNode(1);
 
    if (isUnivalTree(root) == 1) {
 
        cout << "YES";
    }
    else {
 
        cout << "NO";
    }
 
    return 0;
}

C#

// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Structure of a tree node
    static class Node {
        int data;
        Node left;
        Node right;
    };
 
    // Function to insert a new node
    // in a binary tree
    static Node newNode(int data)
    {
        Node temp = new Node();
        temp.data = data;
        temp.left = temp.right = null;
        return (temp);
    }
 
    // Function to check If the tree
    // is univalued or not
    static boolean isUnivalTree(Node root)
    {
 
        // If tree is an empty tree
        if (root == null) {
            return true;
        }
 
        // Store nodes at each level
        // of the tree
        Queue q = new LinkedList<>();
 
        // Insert root node
        q.add(root);
 
        // Stores value of root node
        int rootVal = root.data;
 
        // Traverse the tree using BFS
        while (!q.isEmpty()) {
 
            // Stores front element
            // of the queue
            Node currRoot = q.peek();
 
            // If value of  traversed node
            // not equal to value of root node
            if (currRoot.data != rootVal) {
                return false;
            }
 
            // If left subtree is not NULL
            if (currRoot.left != null) {
 
                // Insert left subtree
                q.add(currRoot.left);
            }
 
            // If right subtree is not NULL
            if (currRoot.right != null) {
 
                // Insert right subtree
                q.add(currRoot.right);
            }
 
            // Remove front element
            // of the queue
            q.remove();
        }
 
        return true;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /*
                    1
                  /   \
                 1     1
               /  \     \
              1    1     1
        */
        Node root = newNode(1);
        root.left = newNode(1);
        root.right = newNode(1);
        root.left.left = newNode(1);
        root.left.right = newNode(1);
        root.right.right = newNode(1);
 
        if (isUnivalTree(root)) {
            System.out.print("YES");
        }
        else {
            System.out.print("NO");
        }
    }
}
 
// This code is contributed by Dharanendra L V.

Javascript

# Python program for the above approach
 
# Structure of a tree node
class node:
     
    # Function to insert a new node
    # in a binary tree
    def __init__(self, x):
        
        self.data = x
        self.left = None
        self.right = None
 
# Function to check If the tree
# is univalued or not
def isUnivalTree(root):
     
    # If tree is an empty tree
    if(root == None):
        return True
     
    # Store nodes at each level
    # of the tree
    q = []
     
    # Insert root node
    q.append(root)
     
    # Stores value of root node
    rootVal = root.data
     
    # Traverse the tree using BFS
    while(len(q) != 0):
         
        # Stores front element
        # of the queue
        currRoot = q[0]
         
        # If value of  traversed node
        # not equal to value of root node
        if (currRoot.data != rootVal):
            return False
         
        # If left subtree is not NULL
        if (currRoot.left != None):
             
            # Insert left subtree
            q.append(currRoot.left)
         
        # If right subtree is not NULL
        if(currRoot.right != None):
             
            # Insert right subtree
            q.append(currRoot.right)
         
        # Remove front element
        # of the queue
        q.pop(0)
     
    return True
 
# Driver Code
if __name__ == '__main__':
     
    #
    #                1
    #              /   \
    #             1     1
    #           /  \     \
    #          1    1     1
         
    root=node(1)
    root.left= node(1)
    root.right = node(1)
    root.left.left = node(1)
    root.left.right = node(1)
    root.right.right = node(1)
     
    if(isUnivalTree(root)):
        print("YES")
    else:
        print("NO")
 
# This code is contributed by avanitrachhadiya2155
输出:
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Structure of a tree node
  class Node
  {
    public int data;
    public Node left;
    public Node right;
  };
 
  // Function to insert a new node
  // in a binary tree
  static Node newNode(int data)
  {
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return (temp);
  }
 
  // Function to check If the tree
  // is univalued or not
  static bool isUnivalTree(Node root)
  {
 
    // If tree is an empty tree
    if (root == null)
    {
      return true;
    }
 
    // Store nodes at each level
    // of the tree
    Queue q = new Queue();
 
    // Insert root node
    q.Enqueue(root);
 
    // Stores value of root node
    int rootVal = root.data;
 
    // Traverse the tree using BFS
    while (q.Count != 0)
    {
 
      // Stores front element
      // of the queue
      Node currRoot = q.Peek();
 
      // If value of  traversed node
      // not equal to value of root node
      if (currRoot.data != rootVal)
      {
        return false;
      }
 
      // If left subtree is not NULL
      if (currRoot.left != null)
      {
 
        // Insert left subtree
        q.Enqueue(currRoot.left);
      }
 
      // If right subtree is not NULL
      if (currRoot.right != null)
      {
 
        // Insert right subtree
        q.Enqueue(currRoot.right);
      }
 
      // Remove front element
      // of the queue
      q.Dequeue();
    }
 
    return true;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
 
    /*
                    1
                  /   \
                 1     1
               /  \     \
              1    1     1
        */
    Node root = newNode(1);
    root.left = newNode(1);
    root.right = newNode(1);
    root.left.left = newNode(1);
    root.left.right = newNode(1);
    root.right.right = newNode(1);
 
    if (isUnivalTree(root))
    {
      Console.Write("YES");
    }
    else
    {
      Console.Write("NO");
    }
  }
}
 
// This code is contributed by 29AjayKumar

时间复杂度: O(N)
辅助空间: O(N)