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-subtrees/

题解:

求Uni-value subtree的个数。对树来说这求count的首先思路就是递归了,不过这里要另外构造一个辅助函数来判断root为顶点的subtree是否是Uni-value subtree,假如是Uni-value的subtree,则结果可以+1,否则,我们返回递归求出的左子树的count和右节点的count。假如是Python的话可以一边计算一边返回。Java写起来可能稍微麻烦点。

Time Complexity - O(n), Space Complexity - O(1).

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        if(root == null)
            return 0;
        if(root.left == null && root.right == null)
            return 1;
        if(root.left == null) {
            if(isUniValueSubtree(root))
                return countUnivalSubtrees(root.right) + 1;
            else
                return countUnivalSubtrees(root.right);
        } else if (root.right == null) {
            if(isUniValueSubtree(root))
                return countUnivalSubtrees(root.left) + 1;
            else
                return countUnivalSubtrees(root.left);
        } else {
            if(isUniValueSubtree(root))
                return countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right) + 1;
            else
                return countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right);
        }
    }

    private boolean isUniValueSubtree(TreeNode root) {
        if(root == null)
            return true;
        if(root.left == null && root.right == null)
            return true;
        else if (root.left != null && root.right != null) {
            if(root.val == root.left.val && root.val == root.right.val)
                return isUniValueSubtree(root.left) && isUniValueSubtree(root.right);
            else
                return false;
        } else if (root.left == null) {
            if(root.right.val == root.val)
                return isUniValueSubtree(root.right);
            else
                return false;
        } else {
            if(root.left.val == root.val)
                return isUniValueSubtree(root.left);
            else
                return false;
        }
    }
}

Update: 优化一下

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        if(root == null)
            return 0;
        if(root.left == null && root.right == null)
            return 1;
        int res = countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right) ;
        return isUniValueSubtree(root) ? res + 1 : res;
    }

    private boolean isUniValueSubtree(TreeNode root) {
        if(root == null)
            return true;
        if(root.left == null && root.right == null)
            return true;
        if(isUniValueSubtree(root.left) && isUniValueSubtree(root.right)) {
            if(root.left != null && root.right != null)
                return (root.left.val == root.right.val) && (root.left.val == root.val);
            else if(root.left != null)
                return root.left.val == root.val;
            else
                return root.right.val == root.val;
        }
        return false;
    }
}

Update: 再优化一下。注意判断两个子树是否都为Uni-value subtree的时候用了 ‘&‘,这样才能判断两个条件,否则第一个条件为false时就不判断第二个了。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int count = 0;
    public int countUnivalSubtrees(TreeNode root) {
        if(root == null)
            return 0;
        isUniValueSubtree(root);
        return count;
    }

    private boolean isUniValueSubtree(TreeNode root) {
        if(root == null)
            return true;

        if(isUniValueSubtree(root.left) & isUniValueSubtree(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;
    }
}

题外话:

这道题题号是250,马克一下。

Reference:

https://leetcode.com/discuss/66805/my-java-solution-using-a-boolean-helper-function

https://leetcode.com/discuss/68057/very-easy-java-solution-post-order-recursion

https://leetcode.com/discuss/63286/7-line-accepted-code-in-java

https://leetcode.com/discuss/52210/c-one-pass-recursive-solution

https://leetcode.com/discuss/50241/recursive-java-solution-with-explanation

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

https://leetcode.com/discuss/50420/java-11-lines-added

https://leetcode.com/discuss/68057/very-easy-java-solution-post-order-recursion

https://github.com/google/google-java-format

https://leetcode.com/discuss/55213/my-ac-java-code

https://leetcode.com/discuss/53431/java-solution-with-dfs

https://leetcode.com/discuss/50452/ac-clean-java-solution

时间: 2024-10-13 01:43:49

250. Count Univalue Subtrees的相关文章

[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

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

[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] 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] 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 锁掉的题目清单

也刷leetcode, 先把锁掉的题目留备份好了: 156 Binary Tree Upside Down  [1] Problem: Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tre

过中等难度题目.0310

  .   8  String to Integer (atoi)    13.9% Medium   . 151 Reverse Words in a String      15.7% Medium     . 288 Unique Word Abbreviation      15.8% Medium     . 29 Divide Two Integers      16.0% Medium     . 166 Fraction to Recurring Decimal      17.