663. Equal Tree Partition 能否把树均分为求和相等的两半
Posted immiao0319
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 on
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
以为是传统的dc-路径求和,没想到是分成几个函数来做。完全没想到。
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[一句话思路]:
getTotal(root.left) + getTotal(root.right) + root.val通过自定义的函数名来进行traverse
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 先退出再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; } }
以上是关于663. Equal Tree Partition 能否把树均分为求和相等的两半的主要内容,如果未能解决你的问题,请参考以下文章
java 663. Equal Tree Partition.java
[leetcode-663-Equal Tree Partition]
663. Equal Tree Partition 能否把树均分为求和相等的两半
LeetCode Partition Equal Subset Sum