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
|