250. Count Univalue Subtrees
Posted 鱼与海洋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
.
/** * 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的主要内容,如果未能解决你的问题,请参考以下文章
[LC] 250. Count Univalue Subtrees