三刷
100.00 %
class Solution {
public int countUnivalSubtrees(TreeNode root) {
int[] count = new int[1];
helper(root, count);
return count[0];
}
// Add current subtree to result
// Return if current subtree is a univalsubtree
private boolean helper(TreeNode node, int[] count) {
if (node == null) {
return true;
}
if (node.left == null && node.right == null) {
count[0]++;
return true;
}
boolean left = helper(node.left, count);
boolean right = helper(node.right, count);
if ((node.left == null || node.left.val == node.val && left)
&& (node.right == null || node.right.val == node.val && right)) {
count[0]++;
return true;
}
return false;
}
}
Version #2(better)
12.05 %
public class Solution {
private int count;
public int countUnivalSubtrees(TreeNode root) {
//current node is the root of a UnivalSubtree:
//left & right children are (null || UnivalSubtrees) & value equals to current node
//return boolean -> is not UnivalSubtree
if (root == null) return 0;
count = 0;
countUnivalSubtreesHelper(root);
return count;
}
private boolean countUnivalSubtreesHelper(TreeNode root) {
if (root == null) return true;
boolean left = countUnivalSubtreesHelper(root.left);
boolean right = countUnivalSubtreesHelper(root.right);
if (left && right) {
if ((root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)) {
count += 1;
return true;
}
}
return false;
}
}
Version #1
对leaf的判断写的不够简洁,其实这道题直接把base case交给root == null就可以了
更新版看Version #2
12.05 %
public class Solution {
private int count;
public int countUnivalSubtrees(TreeNode root) {
//current node is the root of a UnivalSubtree:
//left & right children are (null || UnivalSubtrees) & value equals to current node
//return boolean -> is not UnivalSubtree
if (root == null) return 0;
count = 0;
countUnivalSubtreesHelper(root);
return count;
}
private boolean countUnivalSubtreesHelper(TreeNode root) {
if (root.left == null && root.right == null) {
count += 1;
return true;
}
boolean left = root.left == null ? true : countUnivalSubtreesHelper(root.left);
boolean right = root.right == null ? true : countUnivalSubtreesHelper(root.right);
if (left && right) {
if ((root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)) {
count += 1;
return true;
}
}
return false;
}
}
No comments:
Post a Comment