*Count Univalue Subtrees

mac2022-06-30  80

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.

 

public class Solution { public int count = 0; public int countUnivalSubtrees(TreeNode root) { if(root==null)return 0; isUniValue(root); return count; } public boolean isUniValue(TreeNode node) { if(node==null) return true; boolean left = isUniValue(node.left); boolean right = isUniValue(node.right); if(left&&right) { if(node.left!=null&&node.left.val!=node.val)return false; if(node.right!=null&&node.right.val!=node.val)return false; count++; return true; } else return false; } }

reference:https://leetcode.com/discuss/50357/my-concise-java-solution

转载于:https://www.cnblogs.com/hygeia/p/5101107.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)