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

这道题让我们划分等价树,就是说当移除一条边后,被分成的两棵树的结点之和需要相等。通过观察题目中的例子可以发现,如果将每个结点的结点值变成其所有子结点的结点值之和再加上当前的结点值,那么对于例子1来说,根结点的结点值就变成了 30,断开位置的结点就变成了 15,可以发现其实只要断开位置的结点值是根结点值的一半,就存在等价划分。所以这道题的难点就是更新每个结点的结点值,可以使用递归来做。博主最开始使用的是 unordered_set,把更新后的每个结点值都存入集合中,但是对于 test case: [0, 1, -1] 会 fail, 仔细分析下这个 case,发现更新后的根结点值还是0,而且0已经被存入集合了,而0除以2还是0,在集合中存在,会返回 true,但其实这棵树是不能等价划分的。0的情况确实比较特殊,所以这里要使用 HashMap,建立更新后的结点值和其出现次数之间的映射,这样只有 HashMap 中0的个数大于1的时候,才返回 true。这样完美的避开了根结点为0的陷阱,Perfect!参见代码如下:

解法一:

class Solution {
public:
bool checkEqualTree(TreeNode* root) {
unordered_map<int, int> m;
int sum = helper(root, m);
if (sum == ) return m[] > ;
return (sum % == ) && m.count(sum / );
}
int helper(TreeNode* node, unordered_map<int, int>& m) {
if (!node) return ;
int cur = node->val + helper(node->left, m) + helper(node->right, m);
++m[cur];
return cur;
}
};

我们也可以使用 stack 来做,将所有的结点和存入到栈中,然后依次出栈,看是否有结点和正好等于 sum/2,这里还是要注意当 sum=0 的情况同时根结点值又正好是0的情况,最简单的处理办法就是将栈顶元素提前移除,这样就不会有 sum=sum/2 这种情况发生了,参见代码如下:

解法二:

class Solution {
public:
bool checkEqualTree(TreeNode* root) {
stack<int> st;
int sum = helper(root, st);
st.pop();
if (sum % != ) return false;
while (!st.empty()) {
if (st.top() == sum / ) return true;
st.pop();
}
return false;
}
int helper(TreeNode* node, stack<int>& st) {
if (!node) return ;
st.push(helper(node->left, st) + helper(node->right, st) + node->val);
return st.top();
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/663

参考资料:

https://leetcode.com/problems/equal-tree-partition/

https://leetcode.com/problems/equal-tree-partition/discuss/149437/Logical-Thinking-with-Java-Code-Beats-97.25

https://leetcode.com/problems/equal-tree-partition/discuss/106727/JavaC%2B%2B-Simple-solution-with-only-one-HashMaplessgreater.

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Equal Tree Partition 划分等价树的更多相关文章

  1. [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 tw ...

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

    [抄题]: Given a binary tree with n nodes, your task is to check if it's possible to partition the tree ...

  3. 【LeetCode】663. Equal Tree Partition 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

  4. LeetCode Same Tree (判断相同树)

    题意:如题 思路:递归解决,同判断对称树的原理差不多.先保证当前两个结点是相等的,再递归保证两左结点是相等的,再递归保证右结点是相等的. /** * Definition for a binary t ...

  5. LeetCode: Binary Tree Traversal

    LeetCode: Binary Tree Traversal 题目:树的先序和后序. 后序地址:https://oj.leetcode.com/problems/binary-tree-postor ...

  6. 【LeetCode】Symmetric Tree 推断一棵树是否是镜像的

    题目:Symmetric Tree <span style="font-size:18px;"><span style="font-size:18px; ...

  7. 【LeetCode】208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,Trie, 前缀树,字典树,20 ...

  8. [BZOJ3754]Tree之最小方差树

    3754: Tree之最小方差树 Time Limit: 20 Sec  Memory Limit: 256 MBSubmit: 402  Solved: 152[Submit][Status][Di ...

  9. 【LeetCode】86. Partition List 解题报告(Python)

    [LeetCode]86. Partition List 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http:// ...

随机推荐

  1. [bzoj1565][NOI2009]植物大战僵尸_网络流_拓扑排序

    植物大战僵尸 bzoj1565 题目大意:给你一张网格图,上面种着一些植物.你从网格的最右侧开始进攻.每个植物可以对僵尸提供能量或者消耗僵尸的能量.每个植物可以保护一个特定网格内的植物,如果一个植物被 ...

  2. C#,DataHelper,一个通用的帮助类,留个备份。

    using System; using Newtonsoft.Json; using System.IO; using System.Text; namespace CarHailing.Base { ...

  3. 如何使用maven搭建web项目

    博客园注册了有二十多天了,还没有写过博客,今天就发一篇,也便于后面查找笔记. 我个人已经做了几年的java web开发了,由于所在的公司是业务型公司,用的都是一些老旧的稳定技术,很少接触到稍微新点的内 ...

  4. RabbitMQ封装实战

    先说下背景:上周开始给项目添加曾经没有过的消息中间件.虽然说,一路到头非常容易,直接google,万事不愁~可是生活远不仅是眼前的"苟且".首先是想使用其他项目使用过的一套对mq封 ...

  5. servlet本质

    首先我们先要知道servlet是什么,这有两种解释.一是目前大多数人所说的,一个实现了servlet接口的类就可以叫作servlet.二,servlet只是一个接口.那么看起来这两点都和servlet ...

  6. UI事务重叠引发的crash

    在ios开发的世界里,通过动画来切换界面使我们早就习以为常的事情,但动画将一个原本同步执行的事务,变成一个异步事务,并由此引发了一系列的陷阱. 最近对公司产品的crashlytics报告进行了一些分析 ...

  7. 20145237 《Java程序设计》第2周学习总结

    教材学习内容总结 本周我学习了java的基础语法.分为类型.变量与运算符,流程控制. 一.类型:1.Java可以区分为基本类型和类类型.类类型也称作参考类型.2.Java中基本类型主要是整数.字节.浮 ...

  8. Flask 学习 十五 性能

    记录影响性能的数据库查询 app/main/views.py from flask_sqlalchemy import get_debug_queries @main.after_app_reques ...

  9. 【iOS】swift 74个Swift标准库函数

    本文译自 Swift Standard Library: Documented and undocumented built-in functions in the Swift standard li ...

  10. slf4j 与 log4j2 基本用法

    简单的说 log4j2 是log4j2的升级版,解决了部分性能问题和部分死锁问题,其使用方式与使用配置与log4j相同. 建议使用maven依赖直接使用log4j2 <dependency> ...