/* * 250.Count Univalue Subtrees * 2016-7-21 by Mingyang * 先列出我的解法:自底向上,而且使用了二维数组来进行传递,第一个数有0,1两种可能性 * 0就表示root节点的sub不是uni的,1就表示是uni的,第二个就表示的是个数 */ public static int countUnivalSubtrees(TreeNode root){ if(root==null) return 0; int[] res=uniHelper(root); return res[1]; } public static int[] uniHelper(TreeNode root) { int[] res=new int[2]; if(root==null) return res; if(root.left==null&&root.right==null){ res[0]=1; res[1]=1; return res; } //first index means 1 is uni 0 is not second is number of nodes int[] left=uniHelper(root.left); int[] right=uniHelper(root.right); if(root.left==null){ if(right[0]==1&&root.val==root.right.val){ res[0]=1; res[1]=right[1]+1; }else{ res[0]=0; res[1]=right[1]; } return res; } if(root.right==null){ if(left[0]==1&&root.val==root.left.val){ res[0]=1; res[1]=left[1]+1; }else{ res[0]=0; res[1]=left[1]; } return res; } if(root.val==root.left.val&&root.val==root.right.val&&left[0]==1&&right[0]==1){ res[1]=left[1]+right[1]+1; res[0]=1; }else{ res[1]=left[1]+right[1]; res[0]=0; } return res; } /* * 优化版本!!!!!!!!!!! * 只有两种情况才加加,一种就是我们遇到叶子节点的时候,另一种就是我们遇到三个都相等的节点的时候 */ private int count = 0; public int countUnivalSubtrees1(TreeNode root) { unival(root); return count; } private boolean unival(TreeNode root) { if (root == null) return true; if (root.left == null && root.right == null) { count++; return true; } boolean left = unival(root.left);//自底向上第一步,走到最底的那一层 boolean right = unival(root.right); if (left && right && (root.left == null || root.left.val == root.val)&& (root.right == null || root.right.val == root.val)) { count++; return true; } return false; }