Equal Tree Partition解题报告

2017-09-23  本文已影响23人  黑山老水

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;
    }
上一篇下一篇

猜你喜欢

热点阅读