首页 热点专区 小学知识 中学知识 出国留学 考研考公
您的当前位置:首页正文

Equal Tree Partition解题报告

2024-12-15 来源:要发发知识网

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;
    }
显示全文