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.
To check all nodes of the subtree, we need to adopt the DFS method since we cannot finalize the answer until all nodes are visited.
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.
Last updated