Check if Binary Tree is Uni-valued

BINARY TREE
DEPTH-FIRST SEARCH

Problem

This function checks whether all nodes in a given binary tree have the same value, making it a uni-valued tree.

It traverses the tree to compare the value of each node with the root node's value.

If all nodes match the root value, the tree is uni-valued, and the function returns true; otherwise, it returns false.

Examples

isUnivalTree([3,3,3,3,3,null,3]) // true // Why? Every node in the tree has the value 3. Hence, it's a uni-valued tree. isUnivalTree([4,4,4,4,null,null,5]) // false // Why? Although most nodes have the value 4, // there's one node with a value 5, // so it isn't a uni-valued tree.
Loading...
3
3
3
3
3
0
3