LeetCode #250 Count Univalue Subtrees 統計同值子樹 250 Count Univalue Subtrees 統計同值子樹

250 Count Univalue Subtrees 統計同值子樹

Description:

Given the root of a binary tree, return the number of uni-value subtrees.

A uni-value subtree means all nodes of the subtree have the same value.

Example:

Example 1:

[圖片上傳失敗...(image-20ad3f-1667312129069)]

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

Example 2:

Input: root = []
Output: 0

Example 3:

Input: root = [5,5,5,5,5,null,5]
Output: 6

Constraints:

The number of the node in the tree will be in the range [0, 1000].
-1000 <= Node.val <= 1000

題目描述:

給定一個二叉樹,統計該二叉樹數值相同的子樹個數。

同值子樹是指該子樹的所有節點都擁有相同的數值。

示例:

輸入: root = [5,1,5,5,5,null,5]

              5
             / \
            1   5
           / \   \
          5   5   5

輸出: 4

思路:

遞歸後序遍歷
當遍歷到空結點時返回 true
先遍歷左子樹, 再遍歷右子樹, 最後遍歷根結點
如果爲葉子結點爲 true, 計數器加 1
從葉子結點往上遍歷, 子樹值完全相同的計數器加 1
即左子樹右子樹和根結點值相等
時間複雜度爲 O(n), 空間複雜度爲 O(n), 最差情況樹退化爲鏈表

代碼:

C++:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution 
{
public:
    int countUnivalSubtrees(TreeNode* root) 
    {
        result = 0;
        dfs(root);
        return result;
    }
private:
    int result;
    
    bool dfs(TreeNode* root) 
    {
        if (!root) return true;
        bool left = dfs(root -> left), right = dfs(root -> right), cur = (!root -> left or root -> val == root -> left -> val) and (!root -> right or root -> val == root -> right -> val);
        if (cur and left and right) ++result;
        return cur and left and right;
    }
};

Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int result = 0;
    
    public int countUnivalSubtrees(TreeNode root) {
        dfs(root);
        return result;
    }
    
    private boolean dfs(TreeNode root) {
        if (root == null) return true;
        boolean left = dfs(root.left), right = dfs(root.right), cur = (root.left == null || root.val == root.left.val) && (root.right == null || root.val == root.right.val);
        if (cur && left && right) ++result;
        return cur && left && right;
    }
}

Python:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int:
        count = 0
        def dfs(root: Optional[TreeNode]) -> bool:
            nonlocal count
            if not root:
                return True
            left, right = dfs(root.left), dfs(root.right)
            count += (cur := (not root.left or root.val == root.left.val) and (not root.right or root.val == root.right.val)) and left and right
            return cur and left and right
        dfs(root)
        return count
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章