My code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int counter = 0;
public int countUnivalSubtrees(TreeNode root) {
if (root == null) {
return 0;
}
helper(root);
return counter;
}
private int helper(TreeNode root) {
if (root.left == null && root.right == null) {
counter++;
return root.val;
}
else if (root.left == null) {
int ret = helper(root.right);
if (ret == -1) {
return -1;
}
else if (ret != root.val) {
return -1;
}
else {
counter++;
return ret;
}
}
else if (root.right == null) {
int ret = helper(root.left);
if (ret == -1) {
return -1;
}
else if (ret != root.val) {
return -1;
}
else {
counter++;
return ret;
}
}
else {
int ret1 = helper(root.left);
int ret2 = helper(root.right);
if (ret1 == -1 || ret2 == -1) {
return -1;
}
else {
if (ret1 == root.val && ret2 == root.val) {
counter++;
return ret1;
}
else {
return -1;
}
}
}
}
}
post-order recursion
看了下答案,和我差不多的思路,但写的更加简洁,可能有些情况不用再细分了。
Anyway, Good luck, Richardo! — 09/06/2016