Leetcode
  • Leetcode Questions
  • Runtime Screenshots
  • DataStructure
    • Leetcode 394. Decode String
    • Leetcode 225. Implement Stack Using Queues
    • Leetcode 336. Palindrome Pairs
    • Leetcode 316. Remove Duplicate Letters
    • Leetcode 206. Reverse Linked List
    • Leetcode 347. Top K Frequent Elements
    • Leetcode 227. Basic Calculator II
    • Leetcode 224. Basic Calculator
  • Linear
    • Leetcode 23. Merge k Sorted Lists
    • Leetcode 48. Rotate Image
    • Leetcode 6. ZigZag Conversion
    • Leetcode 438. Find All Anagrams in a String
    • Leetcode 189. Rotate Array
    • LeetCode 56. Merge Intervals
    • Leetcode 4. Median of Two Sorted Array
    • Leetcode 3. Longest Substring Without Repeating Characters
    • Leetcode 8. String to Integer (atoi)
    • Leetcode 5. Longest Palindromic Substring
    • Leetcode 11. Container With Most Water
  • Tree
    • Leetcode 103. Binary Tree Zigzag Level Order Traversal
    • Leetcode 508. Most Frequent Subtree Sum
    • Leetcode 226. Invert Binary Tree
    • Leetcode 222. Count Complete Tree Nodes
    • Leetcode 250. Count Univalue Subtrees
    • Leetcode 285. Inorder Successor in BST
    • Leetcode 230. Kth Smallest Element in a BST
    • Leetcode 543. Diameter of Binary Tree
    • Leetcode 199. Binary Tree Right Side View
  • Math
    • Leetcode 50. Power(x, n)
    • Leetcode 166. Fraction to Recurring Decimal
    • Leetcode 7. Reverse Integer
    • Leetcode 360. Sort Transformed Array
    • Leetcode 367. Valid Perfect Square
    • Leetcode 12. Integer to Roman
  • DynamicProgramming
    • Leetcode 10. Regular Expression Matching
    • Leetcode 253. Meeting Rooms II
    • Leetcode 303. Range Sum Query
    • Leetcode 22. Generate Parentheses
  • Graph
    • Leetcode 142. Linked List Cycle II
    • Leetcode 261. Graph Valid Tree
    • Leetcode 339. Nested List Weight Sum
    • Leetcode 207. Course Schedule
  • OODesign
    • Leetcode 295. Find Media From Data Stream
Powered by GitBook
On this page
  • 题目
  • 思路
  • 解答
  • Complexity Analysis
  • 拓展
  • 总结
  • Reference

Was this helpful?

  1. Tree

Leetcode 250. Count Univalue Subtrees

PreviousLeetcode 222. Count Complete Tree NodesNextLeetcode 285. Inorder Successor in BST

Last updated 5 years ago

Was this helpful?

题目

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

思路

这道题和非常相似。我们可以利用递归的方式 DFS遍历子树来判断左右子树是否为uni-value。如果左右两边都是uni-value,我们则需检查当前节点的值与左右子节点是否相同,如果相同,当前节点为根的树 同样也是uni-value。我们可以得到如下的解答。

解答

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

    private boolean isUnivalue(TreeNode node) {
        if (node.left == null && node.right == null) {
            count++;
            return true;
        }
        boolean uni = true;
        if (node.left != null) {
            uni = isUnivalue(node.left) && uni && node.val == node.left.val;
        }
        if (node.right != null) {
            uni = isUnivalue(node.right) && uni && node.val == node.right.val;
        }

        count = (uni) ? count + 1 : count;
        return uni;
    }

    public int countUnivalSubtrees(TreeNode root) {
        if (root == null) return 0;
        isUnivalue(root);
        return count;
    }

}

Complexity Analysis

  • Time Complexity: O(n). 访问单个节点时间为O(1),总共需要访问所有的节点,即O(n).

  • Space Complexity: O(log(n)). 树的每一层我们都需要递归,因此递归需使用树高O(log(n))这么大的stack space.

拓展

如果你觉得复杂的一连串的条件检查非常不好,我们可以进一步优化以上的算法。我们可以在recursive call的时候pass-in parent的val, 用它来和当前节点进行对比,以返回帮助parent判断其是否为uni-value. 代码如下:

class Solution {
    private int count = 0;

    private boolean uniSub(TreeNode node, int parentVal) {
        if (node == null) return false;
        // VERY IMPORTANT: use | instead of ||. | doesn't short circuiting. 
        if (! uniSub(node.left, node.val) | ! uniSub(node.right, node.val)) {
            return false;
        }
        count++;
        return node.val == parentVal;
    }

    public int countUnivalSubtrees(TreeNode root) {
        uniSub(root, 0);
        return count;
    }
}

总结

这道题同样为考察DFS树遍历。不过我们需要根据题目设置合理的条件判断,不多不少刚刚好,并尝试进行优化以得出优美的解答。

Note: VERY IMPORTANT!!! 这道题还需要注意的是条件判断时,&& 和 || 会short-circuits但是 & 和 | 不会。 递归的时候一定注意不要因为short-circuiting而没执行某些部分。

Reference

208-MostFrequentSubTreeSum
Leetcode Official Solution