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:

https://leetcode.com/problems/equal-tree-partition/description/

解题方法:

寻找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;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,478评论 0 23
  • 一直比较喜欢读人物传记,觉得可以从一个当代比较有名的任务身上偷窥一些感受真切的历史,也能在很短的时间之内将一个人的...
    古今泡泡阅读 5,144评论 0 2
  • “等我上了大学,我要打游戏,天天打游戏,打一个月游戏再说,打游戏到天昏地暗!”高二的时候,我对我的弟弟这样说。说...
    1998a阅读 2,372评论 0 0
  • 引言:耶鲁大学一项历时12年的研究发现,爱阅读的人比压根不读书的人平均多活近2年。如果每周读书3.5个小时,死亡风...
    橙蜂破浪阅读 5,300评论 0 2
  • 我的孤独是一个气球 一直变大 和地球那么大 和太阳系那么大 和银河系那么大 和宇宙那么大 甚至要 大过宇宙 然后就...
    森生阅读 2,962评论 0 2