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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
};
Node* newNode( int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return (temp);
}
bool isUnivalTree(Node* root)
{
if (!root) {
return true ;
}
if (root->left != NULL
&& root->data != root->left->data)
return false ;
if (root->right != NULL
&& root->data != root->right->data)
return false ;
return isUnivalTree(root->left)
&& isUnivalTree(root->right);
}
int main()
{
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
import java.util.*;
class GFG
{
static class Node
{
int data;
Node left;
Node right;
};
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return (temp);
}
static boolean isUnivalTree(Node root)
{
if (root == null )
{
return true ;
}
if (root.left != null
&& root.data != root.left.data)
return false ;
if (root.right != null
&& root.data != root.right.data)
return false ;
return isUnivalTree(root.left)
&& isUnivalTree(root.right);
}
public static void main(String[] args)
{
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" );
}
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self .left = None
self .right = None
def isUnivalTree(root):
if ( not root):
return True
if (root.left ! = None and root.data ! = root.left.data):
return False
if (root.right ! = None and root.data ! = root.right.data):
return False
return isUnivalTree(root.left) and isUnivalTree(root.right)
if __name__ = = '__main__' :
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" )
|
C#
using System;
class GFG
{
class Node
{
public int data;
public Node left;
public Node right;
};
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return (temp);
}
static bool isUnivalTree(Node root)
{
if (root == null )
{
return true ;
}
if (root.left != null
&& root.data != root.left.data)
return false ;
if (root.right != null
&& root.data != root.right.data)
return false ;
return isUnivalTree(root.left)
&& isUnivalTree(root.right);
}
public static void Main(String[] args)
{
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" );
}
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .data=data;
this .left= this .right= null ;
}
}
function isUnivalTree(root)
{
if (root == null )
{
return true ;
}
if (root.left != null
&& root.data != root.left.data)
return false ;
if (root.right != null
&& root.data != root.right.data)
return false ;
return isUnivalTree(root.left)
&& isUnivalTree(root.right);
}
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" );
}
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
};
Node* newNode( int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return (temp);
}
bool isUnivalTree(Node* root)
{
if (!root) {
return true ;
}
queue<Node*> q;
q.push(root);
int rootVal = root->data;
while (!q.empty()) {
Node* currRoot = q.front();
if (currRoot->data != rootVal) {
return false ;
}
if (currRoot->left) {
q.push(currRoot->left);
}
if (currRoot->right) {
q.push(currRoot->right);
}
q.pop();
}
return true ;
}
int main()
{
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
import java.io.*;
import java.util.*;
class GFG {
static class Node {
int data;
Node left;
Node right;
};
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return (temp);
}
static boolean isUnivalTree(Node root)
{
if (root == null ) {
return true ;
}
Queue<Node> q = new LinkedList<>();
q.add(root);
int rootVal = root.data;
while (!q.isEmpty()) {
Node currRoot = q.peek();
if (currRoot.data != rootVal) {
return false ;
}
if (currRoot.left != null ) {
q.add(currRoot.left);
}
if (currRoot.right != null ) {
q.add(currRoot.right);
}
q.remove();
}
return true ;
}
public static void main(String[] args)
{
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" );
}
}
}
|
Python3
class node:
def __init__( self , x):
self .data = x
self .left = None
self .right = None
def isUnivalTree(root):
if (root = = None ):
return True
q = []
q.append(root)
rootVal = root.data
while ( len (q) ! = 0 ):
currRoot = q[ 0 ]
if (currRoot.data ! = rootVal):
return False
if (currRoot.left ! = None ):
q.append(currRoot.left)
if (currRoot.right ! = None ):
q.append(currRoot.right)
q.pop( 0 )
return True
if __name__ = = '__main__' :
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" )
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
class Node
{
public int data;
public Node left;
public Node right;
};
static Node newNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return (temp);
}
static bool isUnivalTree(Node root)
{
if (root == null )
{
return true ;
}
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
int rootVal = root.data;
while (q.Count != 0)
{
Node currRoot = q.Peek();
if (currRoot.data != rootVal)
{
return false ;
}
if (currRoot.left != null )
{
q.Enqueue(currRoot.left);
}
if (currRoot.right != null )
{
q.Enqueue(currRoot.right);
}
q.Dequeue();
}
return true ;
}
public static void Main(String[] args)
{
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" );
}
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .data=data;
this .left= this .right= null ;
}
}
function isUnivalTree(root)
{
if (root == null ) {
return true ;
}
let q = [];
q.push(root);
let rootVal = root.data;
while (q.length!=0) {
let currRoot = q[0];
if (currRoot.data != rootVal) {
return false ;
}
if (currRoot.left != null ) {
q.push(currRoot.left);
}
if (currRoot.right != null ) {
q.push(currRoot.right);
}
q.shift();
}
return true ;
}
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" );
}
</script>
|
Time complexity: O(N)
Auxiliary Space: O(N)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Aug, 2022
Like Article
Save Article