LintCode 864: Equal Tree Partition

本文探讨了如何通过一次边的删除将一个给定的二叉树分割成两个子树,使得这两个子树的节点值之和相等。通过深度优先搜索(DFS)算法,我们实现了对二叉树节点值总和的计算,并检查是否可以找到一个非根节点,其子树的值等于总和的一半。

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

  1. Equal Tree Partition

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
Example 1:

Input: {5,10,10,#,#,2,3}
Output: true
Explanation:
origin:
5
/
10 10
/
2 3
two subtrees:
5 10
/ /
10 2 3
Example 2:

Input: {1,2,10,#,#,2,20}
Output: false
Explanation:
origin:
1
/
2 10
/
2 20
Clarification
Binary Tree Representation

Notice
The range of tree node value is in the range of [-100000, 100000].
1 <= n <= 10000
You can assume that the tree is not null

解法1:DFS。判断某非根节点下面的sum为totalSum的一半就行了。
注意:

  1. totalSum可能为0,所以空节点不能存0到sums数组中。
  2. for循环到< sums.size() - 1就可以了,因为只需要考虑非根节点。

代码如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: a TreeNode
     * @return: return a boolean
     */
    bool checkEqualTree(TreeNode * root) {
        int totalSum = helper(root);

        for (int i = 0; i < sums.size() - 1; ++i) {
            if (sums[i] == totalSum / 2) return true;
        }

        return false;
    }

private:
    vector<long long> sums;

    int helper(TreeNode * root) {
        if (!root) return 0;
        if (!root->left && !root->right) {
            sums.push_back(root->val);
            return root->val;
        }
        int res = helper(root->left) + helper(root->right) + root->val;
        sums.push_back(res);
        return res;
    }
};

代码同步在
https://github.com/luqian2017/Algorithm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值