leetcode 663. Equal Tree Partition

本文探讨了一道关于二叉树的问题:如何通过移除一条边将二叉树分为两个子树,使得这两个子树的节点值之和相等。文章提供了一种简单有效的解决方案,并附带了C++实现代码。

摘要生成于 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

比赛的时候,sb了,求每颗子树的和的时候开了个数组用 i+1 和i+2去做下标,真是2啊。说这些都没用....

 

 

其实,这题很简单,记录每个子树的和,如果是总和的1/2那么就能分成两个相等的子树。

/**
 * 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:
    vector<int>v;
    int sum;
    int dfs (TreeNode* root) {
        if (root == NULL) return 0;
        int ans = 0;
        ans += dfs(root->left);
        ans +=dfs(root->right);
        ans += root->val;
        v.push_back(ans);
        return ans;
    }
    bool checkEqualTree(TreeNode* root) {
        sum = dfs(root);
        if (v.size() == 1) return false;
        for (int i = 0; i < v.size(); ++i) {
            if (2*v[i] == sum) return true;
        }
        return false;
    }
};

 

转载于:https://www.cnblogs.com/pk28/p/7399555.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值