250. Count Univalue Subtrees
Posted tobeabetterpig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了250. Count Univalue Subtrees相关的知识,希望对你有一定的参考价值。
Input: root = [5,1,5,5,5,null,5] 5 / 1 5 / 5 5 5 Output: 4 class Solution { int count = 0; // count must be here to be accssible from the functions below public int countUnivalSubtrees(TreeNode root) { helper(root); return count; } private boolean helper(TreeNode root){ // base case if(root == null){ return true; } boolean left_result = helper(root.left); boolean right_result = helper(root.right); if(left_result && right_result){ if(root.left != null && root.left.val != root.val){ return false; } if(root.right != null && root.right.val != root.val){ return false; } count++; return true; } return false; } } ///// others code // dont know why use an int[] array to pass count? public class Solution { public int countUnivalSubtrees(TreeNode root) { int[] count = new int[1]; helper(root, count); return count[0]; } private boolean helper(TreeNode node, int[] count) { if (node == null) { return true; } boolean left = helper(node.left, count); boolean right = helper(node.right, count); if (left && right) { if (node.left != null && node.val != node.left.val) { return false; } if (node.right != null && node.val != node.right.val) { return false; } count[0]++; return true; } return false; } }
以上是关于250. Count Univalue Subtrees的主要内容,如果未能解决你的问题,请参考以下文章
[LC] 250. Count Univalue Subtrees