1110. Delete Nodes And Return Forest
- 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