标签:cas nod tree root return from rom HERE array
Input: root = [5,1,5,5,5,null,5] 5 / 1 5 / \ 5 5 5 Output: 4 class Solution { int count = 0; // count must be here to be accssible from the functions below public int countUnivalSubtrees(TreeNode root) { helper(root); return count; } private boolean helper(TreeNode root){ // base case if(root == null){ return true; } boolean left_result = helper(root.left); boolean right_result = helper(root.right); if(left_result && right_result){ if(root.left != null && root.left.val != root.val){ return false; } if(root.right != null && root.right.val != root.val){ return false; } count++; return true; } return false; } } ///// others code // dont know why use an int[] array to pass count? public class Solution { public int countUnivalSubtrees(TreeNode root) { int[] count = new int[1]; helper(root, count); return count[0]; } private boolean helper(TreeNode node, int[] count) { if (node == null) { return true; } boolean left = helper(node.left, count); boolean right = helper(node.right, count); if (left && right) { if (node.left != null && node.val != node.left.val) { return false; } if (node.right != null && node.val != node.right.val) { return false; } count[0]++; return true; } return false; } }
标签:cas nod tree root return from rom HERE array
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9335053.html