思路很简单,存在最优子结构,用递归自上至下解即可。
如何判断当前root所代表的树是否为uni-value subtree?
1. 检查root和left,right值是否一致
2. left子树和right子树是否都为uni-value
注意第二步,可能left,right为空,写if时要注意
1 class Solution { 2 private int count; 3 public int countUnivalSubtrees(TreeNode root) { 4 uni(root); 5 return count; 6 } 7 8 boolean uni(TreeNode root) { 9 if(root == null) 10 return true; 11 if(root.left ==null && root.right == null) { 12 count++; 13 return true; 14 } 15 bool left = uni(root.left); 16 bool right = uni(root.right); 17 if(left && right && (root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)) { 18 count++; 19 return true; 20 } 21 return false; 22 } 23 }