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

 

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