题目如下:

A tree rooted at node 0 is given as follows:

  • The number of nodes is nodes;
  • The value of the i-th node is value[i];
  • The parent of the i-th node is parent[i].

Remove every subtree whose sum of values of nodes is zero.

After doing so, return the number of nodes remaining in the tree.

Example 1:

Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1]
Output: 2

Constraints:

  • 1 <= nodes <= 10^4
  • -10^5 <= value[i] <= 10^5
  • parent.length == nodes
  • parent[0] == -1 which indicates that 0 is the root.

解题思路:我的方法是递归+动态规划。对于任意一个节点i,记dp[i]为其子树的和,如果j,k....n为其子节点,那么有dp[i] = dp[j] + dp[k] + .... + dp[n] + value[i]。通过递归的方式很容易可以求出每个节点的子树和,相应的可以求出哪些节点的子树和为0。再遍历这些子树的所有节点,并标记为删除的状态,最后统计出状态为删除的节点即可。

代码如下:

class Solution(object):
def deleteTreeNodes(self, nodes, parent, value):
"""
:type nodes: int
:type parent: List[int]
:type value: List[int]
:rtype: int
"""
import sys
sys.setrecursionlimit(1000000)
dic = {}
for i in range(len(parent)):
dic[parent[i]] = dic.setdefault(parent[i],[]) + [i]
dp = [None] * nodes
def getValue(inx):
if inx not in dic:
dp[inx] = value[inx]
return value[inx]
elif dp[inx] != None:
return dp[inx]
count = 0
for child in dic[inx]:
count += getValue(child)
count += value[inx]
dp[inx] = count
return count dic_remove = {} for i in range(nodes):
if dp[i] == None:
dp[i] = getValue(i)
if dp[i] == 0: dic_remove[i] = 1 delete = [0] * nodes def markDelete(inx):
delete[inx] = 1
if inx not in dic:
return
for key in dic[inx]:
markDelete(key) for inx in dic_remove.iterkeys():
markDelete(inx)
res = sum(delete)
return nodes - res

最新文章

  1. [自翻]fasthttp中文文档(持续更新)
  2. Python3 基本数据类型
  3. 【krpano】高德地图导航插件(源码+介绍+预览)
  4. 并查集 poj2236
  5. 使用delphi+intraweb进行微信开发1~4代码示例
  6. celery简单应用
  7. EF6+MYSQL之初体验
  8. HTML5——多次定位请求
  9. atomic和nonatomic的区别
  10. HackerRank &quot;Minimum Average Waiting Time&quot; !
  11. sass中出现的中文问题
  12. angularjs学习总结(~~很详细的教程)
  13. Cocos2d-x v3.0正式版尝鲜体验【1】 环境搭建和新建项目
  14. 理解Java多态
  15. 对 List 、Set、Map 的理解
  16. 【python】字典dict
  17. nginx 学习 不断更新
  18. VMware虚拟机安装CentOS 6.9图文教程
  19. Windows共享设置
  20. safe close tcp connection

热门文章

  1. C#4.0中的协变和逆变
  2. 将对象以json格式写入到文件中
  3. 利用微信web开发者工具调试企业微信页面
  4. FFmpeg4.0笔记:本地媒体文件解码、帧格式转换、重采样、编码、封装、转封装、avio、硬解码等例子
  5. Hive 教程(六)-Hive Cli
  6. Max History CodeForces - 938E (组合计数)
  7. Docker:Swarm + Stack 一站式部署容器集群
  8. 基于EPICS实现西门子S7通信
  9. selenium自动化测试工具模拟登陆爬取当当网top500畅销书单
  10. KPI VS OKR