LeetCode 0250. Count Univalue Subtrees Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0250. Count Univalue Subtrees

Description

Given the root of a binary tree, return the number of uni-value subtrees.

A uni-value subtree means all nodes of the subtree have the same value.

 

Example 1:

Input: root = [5,1,5,5,5,null,5]
Output: 4

Example 2:

Input: root = []
Output: 0

Example 3:

Input: root = [5,5,5,5,5,null,5]
Output: 6

 

Constraints:

  • The number of the node in the tree will be in the range [0, 1000].
  • -1000 <= Node.val <= 1000

Solutions

Solution 1

PythonJavaC++GoTypeScriptJavaScript
# 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 countUnivalSubtrees(self, root: Optional[TreeNode]) -> int: def dfs(root): if root is None: return True l, r = dfs(root.left), dfs(root.right) if not l or not r: return False a = root.val if root.left is None else root.left.val b = root.val if root.right is None else root.right.val if a == b == root.val: nonlocal ans ans += 1 return True return False ans = 0 dfs(root) return ans(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 !