Check if a Binary Tree is univalued or not - GeeksforGeeks

19 Jan, 2022
Given a binary tree, the task is to check if the binary tree is univalued or not. If found to be true, then print “YES”. Otherwise, print “NO”.
A binary tree is univalued if every node in the tree has the same value.
Example:
Input:  
                   1
                  /  \
                 1    1 
                / \    \
               1   1    1
Output: YES Explanation: The value of all the nodes in the binary tree is equal to 1. Therefore, the required output is YES.
Input:  
                   9
                 /  \
                2   4 
               / \   \
             -1   3   0
Output: NO
  
DFS-based Approach: The idea is to traverse the tree using DFS and check if every node of the binary tree have the same value as the root node of the binary tree or not. If found to be true, then print “YES”. Otherwise, print “NO”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach #include <bits/stdc++.h>using namespace std; // Structure of a tree nodestruct Node {    int data;    Node* left;    Node* right;}; // Function to insert a new node// in a binary treeNode* 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 notbool 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 Codeint 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;}
// Java Program for the above approachimport java.util.*;class GFG{ // Structure of a tree nodestatic class Node{    int data;    Node left;    Node right;}; // Function to insert a new node// in a binary treestatic 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 notstatic 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 Codepublic 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
# python3 Program for the above approach # Structure of a tree nodeclass Node:    def __init__(self, x):        self.data = x        self.left = None        self.right = None # Function to check If the tree# is uni-valued or notdef 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 Codeif __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# Program for the above approachusing System;class GFG{ // Structure of a tree nodeclass Node{    public int data;    public Node left;    public Node right;}; // Function to insert a new node// in a binary treestatic 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 notstatic 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 Codepublic 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
<script> // JavaScript Program for the above approach // Structure of a tree nodeclass Node{    constructor(data)    {        this.data=data;        this.left=this.right=null;    }} // Function to check If the tree// is uni-valued or notfunction isUnivalTree(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/*                1              /   \             1     1           /  \     \          1    1     1    */let root = new Node(1);root.left = new Node(1);root.right = new Node(1);root.left.left = new Node(1);root.left.right = new Node(1);root.right.right = new Node(1); if (isUnivalTree(root)){    document.write("YES");}else{    document.write("NO");}  // This code is contributed by unknown2108 </script>
YES
 
Time complexity: O(N) Auxiliary Space: O(1)
BFS-based Approach: The idea is to traverse the tree using BFS and check if every node of the binary tree have a value equal to the root node of the binary tree or not. If found to be true, then print “YES”. Otherwise, print “NO”. Follow the steps below to solve the problem:
Initialize a queue to traverse the binary tree using BFS.
Insert the root node of the binary tree into the queue.
Insert the left subtree of the tree into queue and check if value of front element of the queue equal to the value of current traversed node of the tree or not. If found to be false, then print “NO”.
Insert the right subtree of the tree into queue and check if value of front element of the queue equal to the value of current traversed node of the tree or not. If found to be false, then print “NO”.
Otherwise, If all the nodes of the tree are traversed and value of each node equal to the value of root node, then print “YES”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Structure of a tree nodestruct Node {    int data;    Node* left;    Node* right;}; // Function to insert a new node// in a binary treeNode* 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 notbool isUnivalTree(Node* root){     // If tree is an empty tree    if (!root) {        return true;    }     // Store nodes at each level    // of the tree    queue<Node*> 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 Codeint 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;}
// Java program for the above approachimport 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<Node> 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.
# Python program for the above approach # Structure of a tree nodeclass 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 notdef 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 Codeif __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 approachusing 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<Node> q = new Queue<Node>();     // 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
<script>// Javascript program for the above approach     // Structure of a tree nodeclass Node{    // Function to insert a new node    // in a binary tree    constructor(data)    {        this.data=data;        this.left=this.right=null;    }} // Function to check If the tree    // is univalued or notfunction isUnivalTree(root){    // If tree is an empty tree        if (root == null) {            return true;        }          // Store nodes at each level        // of the tree        let q = [];          // Insert root node        q.push(root);          // Stores value of root node        let rootVal = root.data;          // Traverse the tree using BFS        while (q.length!=0) {              // Stores front element            // of the queue            let 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 != null) {                  // Insert left subtree                q.push(currRoot.left);            }              // If right subtree is not NULL            if (currRoot.right != null) {                  // Insert right subtree                q.push(currRoot.right);            }              // Remove front element            // of the queue            q.shift();        }          return true;}  // Driver Code /*                    1                  /   \                 1     1               /  \     \              1    1     1        */        let root = new Node(1);        root.left = new Node(1);        root.right = new Node(1);        root.left.left = new Node(1);        root.left.right = new Node(1);        root.right.right = new Node(1);          if (isUnivalTree(root)) {            document.write("YES");        }        else {            document.write("NO");        }   // This code is contributed by patel2127</script>
YES
 
Time complexity: O(N) Auxiliary Space: O(N)
mohit kumar 29
29AjayKumar
dharanendralv23
avanitrachhadiya2155
unknown2108
patel2127
sumitgumber28
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Election algorithm and distributed processing
Introduction to Internet of Things (IoT) | Set 1
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Introduction to Parallel Computing