您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页Equal Tree Partition解题报告

Equal Tree Partition解题报告

来源:二三四教育网

Description:

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:

    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.

Link:

解题方法:

寻找sum为root树sum / 2的节点,如果有,返回true,否则返回false。
注意防止以下情况:

    0
  /   \
-1     1

Time Complexity:

O(N)

完整代码:

bool checkEqualTree(TreeNode* root) 
    {
        if(!root)
            return false;
        unordered_set<int> record;
        int sum = helper(root, record);
        if(sum & 2 != 0)
            return false;
        return (record.find(sum / 2) != record.end());
    }
    int helper(TreeNode* root, unordered_set<int>& record)
    {
        int left = 0, right = 0;
        if(root->left)
        {
            left = helper(root->left, record);
            record.insert(left);
        }
        if(root->right)
        {
            right = helper(root->right, record);
            record.insert(right);
        }
        return root->val + left + right;
    }

Copyright © 2019- how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务