DELETE NODES AND RETURN FOREST | LEETCODE # 1110 | PYTHON DFS SOLUTION

Поділитися
Вставка
  • Опубліковано 12 вер 2024

КОМЕНТАРІ • 14

  • @StellasAdi18
    @StellasAdi18 2 роки тому +3

    Not the easiest problem… feels easy the way you explained. Thanks for explaining it.

  • @rsKayiira
    @rsKayiira Рік тому +1

    Great solution this is not easy for me but well explained. Could you please add LC 825 Friends of Appropriate Ages

  • @usamabaig5856
    @usamabaig5856 2 місяці тому

    How is T: O(n) + O(D), if for every node we are checking if its in to_delete then shouldn't it be O(n) * O(D), what am I missing?

  • @Lord-vq5rh
    @Lord-vq5rh 10 місяців тому

    Nice Explanation

  • @cpuneet98
    @cpuneet98 2 місяці тому

    very helpful

  • @MrZiyak99
    @MrZiyak99 2 роки тому +2

    hey so if node.left.val is in to delete why do we set it as a root?

    • @yousifshamoun5376
      @yousifshamoun5376 Рік тому

      If the node.val is in to_delete then is_root will never be checked so we could have set it to anything

    • @floriandubost5484
      @floriandubost5484 Рік тому +1

      Yes, as Yousif said, this is kind of redundant. The code below does not have this and also runs:
      class Solution:
      def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:
      out = []
      to_delete = set(to_delete)
      def dfs(node, is_root):
      if not node:
      return
      if node.val in to_delete:
      dfs(node.left, True)
      dfs(node.right, True)
      else:
      dfs(node.left,False)
      dfs(node.right,False)
      if node.left and node.left.val in to_delete:
      node.left = None
      if node.right and node.right.val in to_delete:
      node.right = None
      if is_root:
      out.append(node)
      dfs(root, True)
      return out

    • @ryantomlinson9426
      @ryantomlinson9426 Рік тому

      +1 to this, it's a bit confusing setting that to root, but no matter what you set it to it still passes. I'd set it to False just for clarity.

    • @somethingNewAndGood
      @somethingNewAndGood Рік тому

      @@floriandubost5484 This is an awesome solution! A bit cleaner as well.

    • @averychen4633
      @averychen4633 7 місяців тому

      @@floriandubost5484 Thank you. I was so confused by the code in the video. Your response is clearer!

  • @seungminchoi8381
    @seungminchoi8381 Рік тому

    Do you know how to do this without modifying the given tree?

    • @lavanyam3224
      @lavanyam3224 4 місяці тому +1

      I guess the problem expects us to modify the tree coz we've to return the roots after deleting certain nodes.