0250. Count Univalue Subtrees
Medium | Binary Tree + DFS | 24 ms (99.41%), 14.4 MB (72.31%)
Source: LeetCode - Count Univalue Subtrees GitHub: Solution / Performance
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.
First, note that leaf nodes have a valid uni-value subtree.
To make sure an internal node has a valid uni-value subtree, we pass parent nodes' values into the DFS iteration of child nodes to check.
In each DFS iteration, we first check whether the left- and right- nodes have uni-value subtrees. Then, we use the parent node's value to compare with the current node's value.
class Solution:
def countUnivalSubtrees(self, root: TreeNode) -> int:
# (base case)
if not root: return 0
if not root.left and not root.right: return 1
# ==================================================
# Binary Search Tree + DFS =
# ==================================================
# time : O(n)
# space : O(H)
self.unival = 0
self.dfs(root, root.val)
return self.unival
def dfs(self, node: TreeNode, preVal: int) -> bool:
if not node: return True
left = self.dfs(node.left, node.val)
right = self.dfs(node.right, node.val)
if not left or not right:
return False
self.unival += 1
return node.val == preVal
Last updated
Was this helpful?