Algorithm


Problem Name: 965. Univalued Binary Tree

Problem Link: https://leetcode.com/problems/univalued-binary-tree/


A binary tree is uni-valued if every node in the tree has the same value.

Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.

 

Example 1:

Input: root = [1,1,1,1,1,null,1]
Output: true

Example 2:

Input: root = [2,2,2,5,2]
Output: false

 

Constraints:

  • The number of nodes in the tree is in the range [1, 100].
  • 0 <= Node.val < 100
 

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public boolean isUnivalTree(TreeNode root) {
    if (root == null) {
      return true;
    }
    return helper(root, root.val);
  }
  
  private boolean helper(TreeNode root, int val) {
    if (root == null) {
      return true;
    }
    if (root.val != val) {
      return false;
    }
    return helper(root.left, val) && helper(root.right, val);
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [1,1,1,1,1,null,1]

Output

x
+
cmd
true

#2 Code Example with Javascript Programming

Code - Javascript Programming


const isUnivalTree = function(root) {
  const arr = []
  dfs(root, arr)
  for(let i = 1; i  <  arr.length; i++) {
    if(arr[i] !== arr[i- 1]) return false
  }
  return true
};

function dfs(node, arr) {
  if(node === null) return
  arr.push(node.val)
  dfs(node.left, arr)
  dfs(node.right, arr)
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [1,1,1,1,1,null,1]

Output

x
+
cmd
true

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def isUnivalTree(self, root):
        """
        :type root: TreeNode
        :rtype: 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)
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [2,2,2,5,2]

Output

x
+
cmd
false

#4 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _0965_UnivaluedBinaryTree
    {
        public bool 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);
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
root = [2,2,2,5,2]

Output

x
+
cmd
false
Advertisements

Demonstration


Previous
#964 Leetcode Least Operators to Express Number Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#966 Leetcode Vowel Spellchecker Solution in C, C++, Java, JavaScript, Python, C# Leetcode