列表

详情


250. 统计同值子树

给定一个二叉树,统计该二叉树数值相同的子树个数。

同值子树是指该子树的所有节点都拥有相同的数值。

示例:

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

              5
             / \
            1   5
           / \   \
          5   5   5

输出: 4

相似题目

另一棵树的子树

最长同值路径

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/** * 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) { } };

cpp 解法, 执行用时: 4 ms, 内存消耗: 16.5 MB, 提交时间: 2023-10-22 00:08:59

/**
 * 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 Solution1 {
public:
    int countUnivalSubtrees1(TreeNode* root) {
        if (!root) {
            return 0;
        }   

        int res = 0;
        dfs(root, res);

        return res;
    }

private:
    bool isUnivalSubtree(TreeNode* root, int val) {
        if (!root) {
            return true;
        }

        if (root->val != val) {
            return false;
        }

        return isUnivalSubtree(root->left, val) && isUnivalSubtree(root->right, val);

    }
    void dfs(TreeNode* root, int& res) {
        if (!root) {
            return;
        }

        bool isUS = isUnivalSubtree(root, root->val);
        res += isUS;

        dfs(root->left, res);
        dfs(root->right, res);
    }
};


class Solution {
public:
    int countUnivalSubtrees(TreeNode* root) {
        if (!root) {
            return 0;
        }   

        int res = 0;
        postOrder(root, root->val, res);

        return res;
    }

private:
    bool postOrder(TreeNode* root, int val, int& res) {
        if (!root) {
            return true;
        }

        auto left = postOrder(root->left, root->val, res);
        auto right = postOrder(root->right, root->val, res);
        if (!left || !right) {
            return false;
        }

        res++; // cur subtree is an unival tree

        return root->val == val; // 不能直接返回true!
    }
};

python3 解法, 执行用时: 48 ms, 内存消耗: 16.1 MB, 提交时间: 2023-10-22 00:08:22

# 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: TreeNode) -> int:
        self.ans = 0
        def dfs(node):
            if not node:
                return None
            if not node.left and not node.right:
                self.ans += 1
                return node.val
            left = dfs(node.left)
            right = dfs(node.right)
            if left == right == node.val or (left is None and right == node.val) or (right is None and left == node.val):
                self.ans += 1
                return node.val
            return inf
        
        dfs(root)
        return self.ans

java 解法, 执行用时: 0 ms, 内存消耗: 39.7 MB, 提交时间: 2023-10-22 00:08:06

/**
 * 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 {
    int count = 0;
    boolean is_valid_part(TreeNode node, int val) {

        // considered a valid subtree
        if (node == null) return true;

        // check if node.left and node.right are univalue subtrees of value node.val
        // note that || short circuits but | does not - both sides of the or get evaluated with | so we explore all possible routes
        if (!is_valid_part(node.left, node.val) | !is_valid_part(node.right, node.val)) return false;

        // if it passed the last step then this a valid subtree - increment
        count++;

        // at this point we know that this node is a univalue subtree of value node.val
        // pass a boolean indicating if this is a valid subtree for the parent node
        return node.val == val;
    }
    public int countUnivalSubtrees(TreeNode root) {
        is_valid_part(root, 0);
        return count;
    }
}

class Solution2 {
    int count = 0;
    boolean is_uni(TreeNode node) {

        //base case - if the node has no children this is a univalue subtree
        if (node.left == null && node.right == null) {

            // found a univalue subtree - increment
            count++;
            return true;   
        }

        boolean is_unival = true;

        // check if all of the node's children are univalue subtrees and if they have the same value
        // also recursively call is_uni for children
        if (node.left != null) {
            is_unival = is_uni(node.left) && is_unival && node.left.val == node.val;
         }

        if (node.right != null) {
            is_unival = is_uni(node.right) && is_unival && node.right.val == node.val;
        }

        // return if a univalue tree exists here and increment if it does
        if (!is_unival) return false;
        count++;
        return true;
    }
    public int countUnivalSubtrees(TreeNode root) {
        if (root == null) return 0;
        is_uni(root);
        return count;
    }
}

python3 解法, 执行用时: 44 ms, 内存消耗: 16.3 MB, 提交时间: 2023-10-22 00:07:05

# 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:
        self.count = 0
        self.is_valid_part(root, 0)
        return self.count


    def is_valid_part(self, node, val):

        # considered a valid subtree
        if node is None: return True

        # check if node.left and node.right are univalue subtrees of value node.val
        if not all([self.is_valid_part(node.left, node.val),
                    self.is_valid_part(node.right, node.val)]):
            return False

        # if it passed the last step then this a valid subtree - increment
        self.count += 1

        # at this point we know that this node is a univalue subtree of value node.val
        # pass a boolean indicating if this is a valid subtree for the parent node
        return node.val == val

python3 解法, 执行用时: 40 ms, 内存消耗: 16.3 MB, 提交时间: 2023-10-22 00:06:51

# 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:
        if root is None: return 0
        self.count = 0
        self.is_uni(root)
        return self.count

    def is_uni(self, node: Optional[TreeNode]) -> bool:

        # base case - if the node has no children this is a univalue subtree
        if node.left is None and node.right is None:

            # found a univalue subtree - increment
            self.count += 1
            return True

        is_uni = True

        # check if all of the node's children are univalue subtrees and if they have the same value
        # also recursively call is_uni for children
        if node.left is not None:
            is_uni = self.is_uni(node.left) and is_uni and node.left.val == node.val

        if node.right is not None:
            is_uni = self.is_uni(node.right) and is_uni and node.right.val == node.val

        # increment self.res and return whether a univalue tree exists here
        self.count += is_uni
        return is_uni

上一题