[LeetCode] 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.

给一个二叉树,求唯一值子树的个数。唯一值子树的所有节点具有相同值。

解法:递归

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int count = 0;
     
    public int countUnivalSubtrees(TreeNode root) {
        if (root == null) return 0;
        isUnival(root);
        return count;
    }
     
    private boolean isUnival(TreeNode root) {
        if (root == null) return true;
        if (isUnival(root.left) & isUnival(root.right)) {
            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;
    }
}  

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        int[] count = new int[] {0};
        isUnivalSubtrees(root,count);
        return count[0];
    }
     
    private boolean isUnivalSubtrees(TreeNode root, int[] count) {
        if(root == null) return true;
         
        boolean left = isUnivalSubtrees(root.left, count);
        boolean right = isUnivalSubtrees(root.right, count);
        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;
            }
            count[0]++;
            return true;
        }
        return false;
    }
}  

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Time:  O(n)
# Space: O(h)
class Solution(object):
    # @param {TreeNode} root
    # @return {integer}
    def countUnivalSubtrees(self, root):
        [is_uni, count] = self.isUnivalSubtrees(root, 0);
        return count;
 
    def isUnivalSubtrees(self, root, count):
        if not root:
            return [True, count]
 
        [left, count] = self.isUnivalSubtrees(root.left, count)
        [right, count] = self.isUnivalSubtrees(root.right, count)
        if self.isSame(root, root.left, left) and \
           self.isSame(root, root.right, right):
                count += 1
                return [True, count]
 
        return [False, count]
 
    def isSame(self, root, child, is_uni):
        return not child or (is_uni and root.val == child.val)

C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Time:  O(n)
// Space: O(h)
 
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countUnivalSubtrees(TreeNode* root) {
        int count = 0;
        isUnivalSubtrees(root, &count);
        return count;
    }
     
    bool isUnivalSubtrees(TreeNode* root, int *count) {
        if (root == nullptr) {
            return true;
        }
        bool left = isUnivalSubtrees(root->left, count);
        bool right = isUnivalSubtrees(root->right, count);
        if (isSame(root, root->left, left) &&
            isSame(root, root->right, right)) {
                ++(*count);
                return true;
        }
        return false;
    }
     
    bool isSame(TreeNode* root, TreeNode* child, bool is_uni) {
        return child == nullptr || (is_uni && root->val == child->val);
    }
};

  

 

类似题目:

[LeetCode] 687. Longest Univalue Path 最长唯一值路径

 

All LeetCode Questions List 题目汇总

posted @   轻风舞动  阅读(1258)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示