A Uni-value subtree means all nodes of the subtree have the same value.
For example:
Given binary tree,
5 / \ 1 5 / \ \ 5 5 5
return
4
.
Show Tags
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int res = 0;
public int countUnivalSubtrees(TreeNode root) {
res = 0;
if (root == null) {
return 0;
}
visit(root);
return res;
}
private int[] visit(TreeNode node) {
if (node.left == null && node.right == null) {
res++;
int ret[] = new int[2];
ret[0] = node.val;
return ret;
} else {
int ret[] = new int[2];
ret[0] = node.val;
if (node.left != null) {
int leftRet[] = visit(node.left);
if (leftRet[0] != node.val || leftRet[1] == -1) {
ret[1] = -1;
}
}
if (node.right != null) {
int rightRet[] = visit(node.right);
if (rightRet[0] != node.val || rightRet[1] == -1) {
ret[1] = -1;
}
}
if (ret[1] == 0) {
res++;
}
return ret;
}
}
}
========
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int res = 0;
public int countUnivalSubtrees(TreeNode root) {
res = 0;
if (root == null) {
return 0;
}
visit(root);
return res;
}
private boolean visit(TreeNode node) {
if (node.left == null && node.right == null) {
res++;
return true;
} else {
boolean ret = true;
if (node.left != null) {
boolean leftRet = visit(node.left);
if (node.left.val != node.val || !leftRet) {
ret = false;
}
}
if (node.right != null) {
boolean rightRet = visit(node.right);
if (node.right.val != node.val || !rightRet) {
ret = false;
}
}
if (ret) {
res++;
}
return ret;
}
}
}
没有评论:
发表评论