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
Not the easiest problem… feels easy the way you explained. Thanks for explaining it.
Great solution this is not easy for me but well explained. Could you please add LC 825 Friends of Appropriate Ages
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?
Nice Explanation
very helpful
hey so if node.left.val is in to delete why do we set it as a root?
If the node.val is in to_delete then is_root will never be checked so we could have set it to anything
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
+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.
@@floriandubost5484 This is an awesome solution! A bit cleaner as well.
@@floriandubost5484 Thank you. I was so confused by the code in the video. Your response is clearer!
Do you know how to do this without modifying the given tree?
I guess the problem expects us to modify the tree coz we've to return the roots after deleting certain nodes.