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