0250. Count Univalue Subtrees
Medium | Binary Tree + DFS | 24 ms (99.41%), 14.4 MB (72.31%)
Last updated
Was this helpful?
Medium | Binary Tree + DFS | 24 ms (99.41%), 14.4 MB (72.31%)
Last updated
Was this helpful?
Source: GitHub:
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.