663. Equal Tree Partition

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:

  1. The range of tree node value is in the range of [-100000, 100000].
  2. 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值