美文网首页
Equal Tree Partition解题报告

Equal Tree Partition解题报告

作者: 黑山老水 | 来源:发表于2017-09-23 12:48 被阅读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;
        }
    

    相关文章

      网友评论

          本文标题:Equal Tree Partition解题报告

          本文链接:https://www.haomeiwen.com/subject/lqrcextx.html