LeetCode 1110. Delete Nodes And Return Forest - 二叉树(Binary Tree)系列题10

给定一个二叉树和一个节点数组,删除所有包含在to_delete中的节点,形成森林。返回剩余森林中各棵树的根节点。本文详细介绍了如何通过前序遍历来解决这个问题,包括处理节点的两种情况:在或不在to_delete中,并解释了如何确定新小树的根节点。
摘要由CSDN通过智能技术生成

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]]

Example 2:

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

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.

题目给定一棵二叉树和一个节点数组to_delete,要求从树中把to_delete中的节点删掉,这样就得一棵棵互不相连的小树。要求返回每棵小树的根节点。

基本思路是利用前序遍历处理每个节点。对于一个节点无外乎两种情况,在或不在to_delete中。为了便于查找节点是否在to_delete中,可以把to_delete中的节点放入一个set中;另外为了便于处理节点之间的连接关系,在遍历过程中还需引入当前节点的父节点

1)节点在to_delete中,说明该节点需要被删掉,如果该节点的父节点不为空,则要把父节点的左子节点或者右子节点赋为空(取决于当前节点是其父节点的哪个子节点)。由于该节点被删掉了,所以在继续遍历其子树时,其子节点的父节点就应该为空。

2)节点不在to_delete中,说明该节点要保留,这时需要看该节点是否为一棵新小树的根节点,这取决于其父节点。如果父节点为空(即被删掉了),那么该节点为一棵新小树的根节点,否则就是一个普通的中间节点,继续往下遍历。

class Solution:
    def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:
        res = []
        delSet = set(to_delete)
        
        def helper(parent, node):
            if not node:
                return
            if node.val in delSet:
                if parent :
                    if parent.left == node:
                        parent.left = None
                    else:
                        parent.right = None
                parent = None
            else:
                if not parent:
                    res.append(node)
                parent = node
            
            helper(parent, node.left)
            helper(parent, node.right)
        helper(None, root)
        
        return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值