LeetCode 1110. Delete Nodes And Return Forest

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.

 

--------------------------------------------

题目不难,反应有些慢,需要迅速想清楚两点:

1. 只有父节点不存在,子节点存在的时候,子节点才有机会作为森林里某棵树的根

2. 遍历完加个返回值,这时候让父节点和被删孩子节点断绝关系也不迟,但是这一步一定要有哦

 

# 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 delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
        to_d,res = set(to_delete),[]
        
        def dfs(root, p_exist):
            if root == None:
                return None
            cur_exist = root.val not in to_d
            if (p_exist == False and cur_exist == True):
                res.append(root)
            root.left = dfs(root.left, cur_exist)
            root.right = dfs(root.right, cur_exist)
            return root if cur_exist else None
        dfs(root, False)
        return res

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章