- 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