[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:

/**
 * 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:

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:

# 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++:

// 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 最长唯一值路径

原文地址:https://www.cnblogs.com/lightwindy/p/9795764.html

时间: 2024-08-26 10:47:11

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

[LeetCode] 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. 这道题让我们求相同值子树的个数,就是所有节点值都相同的子树的个数,之前有道求最大BST子树的题Largest BST

[LeetCode#250] Count Univalue Subtrees

Problem: 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. Analysis: This problem is super simple. But, beca

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. 链接: http://leetcode.com/problems/count-univalue-subtre

[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. * pub

[Locked] Count Univalue Subtrees

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. 分析: 有点像自低向上的动态规划,既然是自底向上,看来用递归访问树的

LeetCode Count Univalue Subtrees

原题链接在这里:https://leetcode.com/problems/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 retur

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

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. Note: The length of path between two nodes is represented by the number of edges between them. Ex

LeetCode:Count Primes - 统计质数数量

1.题目名称 Count Primes(统计质数数量) 2.题目地址 https://leetcode.com/problems/count-primes/ 3.题目内容 英文:Count the number of prime numbers less than a non-negative number, n. 中文:统计正整数n以内(不含n本身)质数的数量 4.一个TLE的方法 从1到n,考察每个数字是否为质数.这个方法由于花费时间较长,不能满足题目中对时间的要求. 一段实现此方法的Jav

C#.NET为List加入扩展方法:获取唯一值

public static class ListTools { /// <summary> /// 获取唯一值列表 /// </summary> /// <param name="strList">原始值</param> /// <returns>唯一值</returns> public static List<T> GetUniqueValue<T>(this List<T>