LeetCode 1110. Delete Nodes And Return Forest解题报告(python)

1110. Delete Nodes And Return Forest

  1. Delete Nodes And Return Forest python solution

题目描述

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.
在这里插入图片描述

解析

本题需要判断的东西有三样,第一该节点是否需要删除;第二该节点是否含有父节点,若不含有父节点,该节点便形成一个新的树。第三判断该节点的位置,是位于左子树还是右子树。

class Solution:
    def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
        ans=[]
        def recurse(tree, parent, location):
            if not tree:
                return 
            if tree.val in to_delete:
                if parent and location==1:
                    parent.left=None
                if parent and location==2:
                    parent.right=None
                
                recurse(tree.left,None,1)
                recurse(tree.right,None,2)
            else:
                if not parent:ans.append(tree)
                recurse(tree.left,tree,1)
                recurse(tree.right,tree,2)
                
        if not root:return []
        recurse(root,None,0)
        return ans

Reference

https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/343422/Python-Solution

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值