https://leetcode.com/problems/count-univalue-subtrees/description/
Given a binary tree, count the number of uni-value subtrees.
A Uni-value subtree means all nodes of the subtree have the same value.
For example:
Given binary tree,
5'''''
/
1 5''''
/
5' 5'' 5'''
5 5 5 5
5
return 4.
典型的后序遍历:从最下层比较 最后"打印" 的概念 (5,5,1) (#,5,5),(5) 从下面的叶子倒推树的结果
root = 5' and 5'' res = 2
root = 1 res = 2 返回FALSE
root = 5''' res = 3
root = 5'''' res= 4
root = 5''''' 因为 ROOT =1 返回FALSE 所以不需要看了 res = 4
time: o(n)
space: o(n)
另外,这道题如果 改成:
5
/
1 5
/
3 5 5
答案也是 4: 3,5 都算"值一样的子树"
1 // node value, count
2 int res ;
3 public int countUnivalSubtrees(TreeNode root) {
4 res = 0;
5 helper(root);
6 return res ;
7 }
8
9 //根 叶子 都要 一样的值,才算一个SUBTREE
10 private boolean helper(TreeNode root) {
11 if (root ==null) return true ;
12 boolean leftCheck = helper(root.left) ;
13 boolean rightCheck = helper(root.right) ;
14 if (leftCheck && rightCheck) {
15 //如果叶子有值,则必须和当前根值一样; 两边叶子如果都没有值,则直接++
16 if (root.left != null && root.left.val != root.val){
17 return false;
18 }
19 if (root.right != null && root.right.val != root.val){
20 return false;
21 }
22 res++ ;
23 return true;
24 }
25 return false;
26 }
重点题,需要反复体会