250. Count Univalue Subtrees
道理上不是特别难,但是因为一边要返回计数一边又要返回是不是univalue所以需要一个helper函数。
1 public class Solution { 2 int cnt = 0; 3 public int countUnivalSubtrees(TreeNode root) { 4 helper(root); 5 return cnt; 6 } 7 8 private boolean helper(TreeNode root) { 9 if(root == null) { 10 return true; 11 } 12 boolean left = helper(root.left); 13 boolean right = helper(root.right); 14 if(left && right) { 15 if(root.left != null && root.val != root.left.val) { 16 return false; 17 } 18 if(root.right != null && root.val != root.right.val) { 19 return false; 20 } 21 cnt++; 22 return true; 23 } 24 return false; 25 } 26 }