LeetCode 0965. Univalued Binary Tree Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0965. Univalued Binary Tree

Description

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

Solutions

Solution 1: DFS

We denote the value of the root node as x, and then design a function dfs(root), which indicates whether the current node's value is equal to x and its left and right subtrees are also univalued binary trees.

In the function dfs(root), if the current node is null, return true; otherwise, if the current node's value is equal to x and its left and right subtrees are also univalued binary trees, return true; otherwise, return false.

In the main function, we call dfs(root) and return the result.

The time complexity is O(n), and the space complexity is O(n), where n is the number of nodes in the tree.

PythonJavaC++GoTypeScriptRust
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isUnivalTree(self, root: Optional[TreeNode]) -> bool: def dfs(root: Optional[TreeNode]) -> bool: if root is None: return True return root.val == x and dfs(root.left) and dfs(root.right) x = root.val return dfs(root)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !