题目如下:

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

【leetcode】1273. Delete Tree Nodes的更多相关文章

  1. 【LeetCode】199. Binary Tree Right Side View 解题报告(Python)

    [LeetCode]199. Binary Tree Right Side View 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/probl ...

  2. 【leetcode】955. Delete Columns to Make Sorted II

    题目如下: We are given an array A of N lowercase letter strings, all of the same length. Now, we may cho ...

  3. 【LeetCode】145. Binary Tree Postorder Traversal

    Difficulty: Hard  More:[目录]LeetCode Java实现 Description https://leetcode.com/problems/binary-tree-pos ...

  4. 【LeetCode】Balanced Binary Tree 解题报告

    [题目] Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced bi ...

  5. 【LeetCode】1110. Delete Nodes And Return Forest 解题报告 (C++)

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

  6. 【leetcode】1110. Delete Nodes And Return Forest

    题目如下: Given the root of a binary tree, each node in the tree has a distinct value. After deleting al ...

  7. 【LeetCode】124. Binary Tree Maximum Path Sum 解题报告 (C++)

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

  8. 【LeetCode】237. Delete Node in a Linked List 解题报告 (Java&Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 设置当前节点的值为下一个 日期 [LeetCode] ...

  9. 【LeetCode】107. Binary Tree Level Order Traversal II 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:迭代 日期 [LeetCode ...

随机推荐

  1. VS2008编译boost1.53

    1. 准备工作:下载boost_1_53_0.zip(bzip2-1.0.6.tar.gz/icu4c-4_4_2-Win32-msvc9.zip/Python-2.5.2.tar.bz2/zlib- ...

  2. zip 命令

    NAME zip - package and compress (archive) files SYNOPSIS         zip [-aABcdDeEfFghjklLmoqrRSTuvVwXy ...

  3. spring5源码分析系列(一)——spring5框架模块

    spring总共大约20个模块,这些模块被整合在核心容器(Core Container).AOP和设备支持.数据访问及集成.Web.报文发送.Test 6个模块集合. 组成Spring框架的每个模块集 ...

  4. Laravel5.5 实现session配置

    \Illuminate\Session\Middleware\StartSession::class,\Illuminate\View\Middleware\ShareErrorsFromSessio ...

  5. redis 学习(8)-- redis 客户端 -- Jedis

    redis 客户端 -- Jedis 1. Jedis 直连 本质是 TCP 连接. 执行流程 创建Jedis对象 通过Jedis执行命令 返回Jedis执行结果 关闭Jedis连接 demo 要使用 ...

  6. 打不开Call Hierarchy和History的解决方法

    Eclipse打不开Call Hierarchy和History的解决方法   工作中一直使用Eclipse,之前都好好的,最近突然出了问题. 一开始是发现按Ctrl+Alt+H打不开Call Hie ...

  7. Postgresql 大小版本升级

    文章结构如下: Postgresql是一个非常活跃的社区开源项目,更新速度很快,每一次版本的更新都会积极的修复旧版本的BUG,性能上也会有不同幅度的提升.10之前的版本由三部分组成,10开始只有两部分 ...

  8. LintCode 6---合并排序数组 II

    import java.util.Arrays; public class Lint6 { /* * 合并两个排序的整数数组A和B变成一个新的数组.新数组也要有序. */ public static ...

  9. 禁止ios10双指缩放

    document.addEventListener('gesturestart', function(event) { event.preventDefault(); });

  10. 帝国cms 重置用户名和密码

    5.1至7.0版本:用phpmyadmin修改phome_enewsuser表里的记录:把password字段的值设为:“322d3fef02fc39251436cb4522d29a71”:把salt ...