663. 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 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:
- The range of tree node value is in the range of [-100000, 100000].
- 1 <= n <= 10000
方法1: hash map
思路:
为了避免第二次遍历,用一个hash来保存所有见过的subtree total。最后直接在hash里面找有没有等于sum / 2的subtree(如果sum是奇数直接返回false)。这里要注意hash本身也包括了整个树的sum,但是这是不符合题意的subtree,因此要在hash里面把sum去掉。这里用了hashmap计数,也可以用一个stack/vector来按顺序记录,那么由于整个遍历顺序是后序的,sum将会是最后一个被推进的数,在查找之前pop一次即可。
/**
* 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 {
private:
unordered_map<int, int> hash;
public:
bool checkEqualTree(TreeNode* root) {
int sum = checkHelper(root);
hash[sum]--;
if (sum % 2 == 0)
return hash[sum / 2] != 0;
return false;
}
int checkHelper(TreeNode* root) {
if (!root) return 0;
int sum = checkHelper(root -> left) + root -> val + checkHelper(root -> right);
hash[sum]++;
return sum;
}
};
/**
* 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 {
private:
vector<int> st;
public:
bool checkEqualTree(TreeNode* root) {
int sum = checkHelper(root);
st.pop_back();
if (sum % 2 == 0)
for (int num: st) {
if (num == sum / 2) return true;
}
return false;
}
int checkHelper(TreeNode* root) {
if (!root) return 0;
int sum = checkHelper(root -> left) + root -> val + checkHelper(root -> right);
st.push_back(sum);
return sum;
}
};