[leetcode] 1110. Delete Nodes And Return Forest

Description

Given the root of a binary tree, each node in the tree has a distinct value.

After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

Return the roots of the trees in the remaining forest. You may return the result in any order.

Example 1:

Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]

Constraints:

  • The number of nodes in the given tree is at most 1000.
  • Each node has a distinct value between 1 and 1000.
  • to_delete.length <= 1000
  • to_delete contains distinct values between 1 and 1000.

分析

题目的意思是:给定一颗二叉树,然后删除给定结点以后,返回剩下的森林。这道题用递归遍历的话,需要分析一下,如果当前节点在待删除的集合中,则把左右节点加入到森林集合里面。如果没有则返回当前节点,返回空。
最后全部遍历完以后,要判断root是否为空,这代表二叉树的根结点是否被删,如果没被删除,要加入到结果集合里面。如果能想到这个就能递归做出来。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def solve(self,root,to_delete,forest):
        if(root is None):
            return root
        root.left=self.solve(root.left,to_delete,forest)
        root.right=self.solve(root.right,to_delete,forest)
        if(root.val in to_delete):
            if(root.left):
                forest.append(root.left)
            if(root.right):
                forest.append(root.right)
            return None
        return root
            
    def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
        forest=[]
        root=self.solve(root,to_delete,forest)
        if(root):
            forest.append(root)
        return forest

参考文献

[LeetCode] Intuitive Python short solution beats 97% submissions

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值