码迷,mamicode.com
首页 > 其他好文 > 详细

663. Equal Tree Partition 能否把树均分为求和相等的两半

时间:2018-09-09 12:06:58      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:equal   int   display   复杂度   color   输出   into   思路   col   

[抄题]:

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 on

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

以为是传统的dc-路径求和,没想到是分成几个函数来做。完全没想到。

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

 

getTotal(root.left) + getTotal(root.right) + root.val通过自定义的函数名来进行traverse

 

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 先退出再expand, checkequal只要有一个true就直接退出了

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

 

通过自定义的函数名来进行traverse,先退出再expand, checkequal只要有一个true就直接退出了 

 

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

 

public long checkEqual(TreeNode root) {
        //exit or expand
        if (root == null || equal) return 0;
        
        long curSum = checkEqual(root.left) + checkEqual(root.right) + root.val;
        if (curSum == targetSum - curSum) {
            equal = true;
            return 0;
        }
        return curSum;
    }

 

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

 

技术分享图片
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    //initialiazation
    boolean equal = false;
    long targetSum = 0;
    
    public boolean checkEqualTree(TreeNode root) {
        targetSum = getSum(root);
        checkEqual(root);
        return equal;
    }
    
    public long getSum(TreeNode root) {
        //exit or expand
        if (root == null) return 0;
        return getSum(root.left) + getSum(root.right) + root.val;
    }
    
    public long checkEqual(TreeNode root) {
        //exit or expand
        if (root == null || equal) return 0;
        
        long curSum = checkEqual(root.left) + checkEqual(root.right) + root.val;
        if (curSum == targetSum - curSum) {
            equal = true;
            return 0;
        }
        return curSum;
    }
}
View Code

 

663. Equal Tree Partition 能否把树均分为求和相等的两半

标签:equal   int   display   复杂度   color   输出   into   思路   col   

原文地址:https://www.cnblogs.com/immiao0319/p/9612564.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!