[LC] 250. Count Univalue Subtrees

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 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.

Example :

Input:  root = [5,1,5,5,5,null,5]

              5
             /             1   5
           /              5   5   5

Output: 4

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int res = 0;
    public int countUnivalSubtrees(TreeNode root) {
        helper(root);
        return res;
    }
    
    private boolean helper(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean left = helper(root.left);
        boolean right = helper(root.right);
        if (left && right) {
            if (root.left != null && root.left.val != root.val) {
                return false;
            }
            if (root.right != null && root.right.val != root.val) {
                return false;
            }
            res += 1;
            return true;
        }
        
        /** another way
        if (left && right && 
           (root.left == null || root.val == root.left.val) && 
           (root.right == null || root.val == root.right.val)) {
            res++;
            return true;
        }
        */
        return false;
    }
}

以上是关于[LC] 250. Count Univalue Subtrees的主要内容,如果未能解决你的问题,请参考以下文章

250. Count Univalue Subtrees

250. Count Univalue Subtrees

250. Count Univalue Subtrees

250.Count Univalue Subtrees

[LeetCode] 250. Count Univalue Subtrees 计算唯一值子树的个数

java 250.计算Univalue Subtrees.java