Univalued Binary Tree

Posted by Bill on March 11, 2023

Univalued Binary Tree

A binary tree is univalued if every node in the tree has the same value.

Return true if and only if the given tree is univalued.

  • Input: [1,1,1,1,1,null,1]
  • Output: true

  • Input: [2,2,2,5,2]
  • Output: false

Java Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
    public boolean isUnivalTree(TreeNode root) {
        int val = root.val;
        if(root.left == null && root.right == null){
            return true;
        }
        if(root.left == null){
            return isUnivalTree(root.right) &&(root.val == root.right.val);
        }
        else if(root.right == null){
            return isUnivalTree(root.left) &&(root.val == root.left.val);
        }
        else{
            return isUnivalTree(root.left) && isUnivalTree(root.right)
                    && (root.val == root.left.val) && (root.val == root.right.val);
        }
    }
}