Given a binary tree, count the number of uni-value subtrees.
A Uni-value subtree means all nodes of the subtree have the same value.
For example:
Given binary tree,
Given binary tree,
5 / \ 1 5 / \ \ 5 5 5
return
4
.
就是对一个树找子树值和root相同的个数, 对于例子中 三个叶节点5都算, 另外一个是root的右儿子 因为它left child为空 right child值跟本身相等
public class Solution { public int countUnivalSubtrees(TreeNode root) { int[] res = new int[1]; if (root == null) { return 0; } helper(root, res); return res[0]; } public boolean helper(TreeNode root, int[] res) { if (root.left == null && root.right == null) { res[0]++; return true; } else if (root.left == null && root.right != null) { if (helper(root.right, res) && root.val == root.right.val) { res[0]++; return true; } else { return false; } } else if (root.right == null && root.left != null) { if (helper(root.left, res) && root.left.val == root.val) { res[0]++; return true; } else { return false; } } else { boolean l = helper(root.left, res);//必须单独列出来因为如果root.left = false 仍要递归root.right以对res进行操作 boolean r = helper(root.right, res); if (l && r && root.val == root.left.val && root.val == root.right.val) { res[0]++; return true; } else { return false; } } } }
没有评论:
发表评论