首页 > 代码库 > 250. Count Univalue Subtrees
250. Count Univalue Subtrees
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,
5 / 1 5 / \ 5 5 5
return 4
.
Hide Tags
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { //post order; int max = 1; public int countUnivalSubtrees(TreeNode root) { if(root == null) return 0; if(root.left == null && root.right == null) return 1; int res = countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right); return isUniTree(root) ? res +1 : res; } public boolean isUniTree(TreeNode root){ if(root == null) return true; if(root.left == null && root.right == null) return true; if(isUniTree(root.left) && isUniTree(root.right)){ if(root.left != null && root.right != null){ return (root.left.val == root.right.val && root.right.val == root.val); }else if(root.left != null) return root.left.val == root.val; else return root.right.val == root.val; } return false; }}
250. Count Univalue Subtrees
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。