- 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的一半就行了。
注意:
- totalSum可能为0,所以空节点不能存0到sums数组中。
- 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
本文探讨了如何通过一次边的删除将一个给定的二叉树分割成两个子树,使得这两个子树的节点值之和相等。通过深度优先搜索(DFS)算法,我们实现了对二叉树节点值总和的计算,并检查是否可以找到一个非根节点,其子树的值等于总和的一半。
3万+

被折叠的 条评论
为什么被折叠?



