Skip to content

965. Univalued Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  bool isUnivalTree(TreeNode* root) {
    if (root == nullptr)
      return true;
    if (root->left != nullptr && root->left->val != root->val)
      return false;
    if (root->right != nullptr && root->right->val != root->val)
      return false;
    return isUnivalTree(root->left) && isUnivalTree(root->right);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public boolean isUnivalTree(TreeNode root) {
    if (root == null)
      return true;
    if (root.left != null && root.left.val != root.val)
      return false;
    if (root.right != null && root.right.val != root.val)
      return false;
    return isUnivalTree(root.left) && isUnivalTree(root.right);
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def isUnivalTree(self, root: TreeNode | None) -> bool:
    if not root:
      return True
    if root.left and root.left.val != root.val:
      return False
    if root.right and root.right.val != root.val:
      return False
    return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)