leetcode 663. Equal Tree Partition

原题:

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 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.

Note:

  1. The range of tree node value is in the range of [-100000, 100000].
  2. 1 <= n <= 10000

思路:

先求出总和,然后第二次进行遍历的时候计算和是不是一半就好

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool checkEqualTree(struct TreeNode* root) {
    if(root->left==NULL&&root->right==NULL)
        return false;
    int getsum1(struct TreeNode* root);
    int sum=getsum(root);
    printf("%d",sum);
    bool getresult(struct TreeNode* root,int sum);
    return getresult(root,sum);
}
int getsum(struct TreeNode* root)
{
    if(root==NULL)
        return 0;
    return getsum(root->left)+root->val+getsum(root->right);
}
bool getresult(struct TreeNode* root,int sum)
{
    int getsum(struct TreeNode*);
    if(root==NULL)
        return false;
    bool result=false;
    if(sum==2*getsum(root))
        result=true;
    return getresult(root->left,sum)||result||getresult(root->right,sum);
}

还希望大家多多留言讨论下,我是一定会回复的。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值