[Leetcode] 663. Equal Tree Partition 解题报告

这篇博客介绍了LeetCode 663题目的解法,探讨如何找到一棵二叉树中能使得分割后两部分和相等的删除边。通过建立哈希表记录子树和,遍历寻找一半总和的节点来实现解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given a binary tree with n nodes, your task is to check if it's possible to partition the tree to two trees which have the equal sum of values after removing exactly one edge on the original tree.

Example 1:

Input:     
    5
   / \
  10 10
    /  \
   2   3

Output: True
Explanation: 
    5
   / 
  10
      
Sum: 15

   10
  /  \
 2    3

Sum: 15

Example 2:

Input:     
    1
   / \
  2  10
    /  \
   2   20

Output: False
Explanation: You can't split the tree into two trees with equal sum after removing exactly one edge on the tree.

Note:

  1. The range of tree node value is in the range of [-100000, 100000].
  2. 1 <= n <= 10000

思路

我们建立一个哈希表,记录每个节点对应的子树的和,然后遍历树中的每一个子节点,一旦发现该子节点的和为整个树的和的一半,就说明找到了一个符合条件的split,从这里切分,可以将整个树划分成为和相等的两棵树。

代码

/**
 * 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:
    bool checkEqualTree(TreeNode* root) {
        unordered_map<TreeNode*, int> hash;     // node -> sum
        int sum = getSum(root, hash);
        if (sum % 2 != 0) {
            return false;
        }
        return canSplit(root, hash, sum / 2);
    }
private:
    bool canSplit(TreeNode* root, unordered_map<TreeNode*, int> &hash, int half_sum) {
        if (root == NULL) {
            return false;
        }
        if (root->left && hash[root->left] == half_sum) {
            return true;
        }
        if (root->right && hash[root->right] == half_sum) {
            return true;
        }
        return canSplit(root->left, hash, half_sum) || canSplit(root->right, hash, half_sum);
    }
    int getSum(TreeNode* root, unordered_map<TreeNode*, int> &hash) {
        if (root == NULL) {
            return 0;
        }
        int left = getSum(root->left, hash);
        int right = getSum(root->right, hash);
        int sum = left + right + root->val;
        hash[root] = sum;
        return sum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值