Delete Nodes And Return Forest - Leetcode 1110 - Python

  Рет қаралды 9,558

NeetCodeIO

NeetCodeIO

Күн бұрын

Пікірлер: 45
@shyamsundarmg1497
@shyamsundarmg1497 6 ай бұрын
5:18 "There's no magic way; it's not just going to magically pop up into your mind, so DON'T BE LAZY; get a piece of paper, draw out some examples, and see what you can come up with." GOLDEN WORDS... I was too lazy and came to look up at the video to see solution without trying much, Thank You NeetCode, this really was a motivation that stirred my ego and I ended up doing the first problem with 100.00% better in time... Lots of love and respect to you Navdeep!!
@aadil4236
@aadil4236 6 ай бұрын
Solved it by myself in O(n) space and O(n) time. Thank you for teaching me Navdeep! I am better than my past self because of NeetCode. Thank you!!
@AKProductionsTelugu
@AKProductionsTelugu 6 ай бұрын
This problem is even easier by following post order traversal get left node get right node check if root needs to be removed if yes, null check and add two children to roots list and return null else return node This way we don't need to maintain two sets TreeNode dfs(TreeNode root) { if(root == null) return null; TreeNode left = dfs(root.left); TreeNode right = dfs(root.right); if(nodesToDelete.contains(root.val)) { if(left != null) trees.add(left); if(right != null) trees.add(right); return null; } root.left = left; root.right = right; return root; }
@DNKF
@DNKF 6 ай бұрын
First! Love super early videos these days. Will start reading the neetcode new chapter tonight.
@NeetCodeIO
@NeetCodeIO 6 ай бұрын
As long as it's not a hard problem I can usually pump these out fast. As difficult it is to solve a LC hard, it's even more time consuming to explain them tbh
@DNKF
@DNKF 6 ай бұрын
@@NeetCodeIO for hard one, sometime I could not figure them out until watching your videos 😅
@chrischika7026
@chrischika7026 6 ай бұрын
@@NeetCodeIO what type of traversal is your solution preorder or postorder ?
@pratyushthakur8478
@pratyushthakur8478 6 ай бұрын
I haven't practiced trees in a while but happy that the daily is making me revise old topics.
@freecourseplatformenglish2829
@freecourseplatformenglish2829 6 ай бұрын
Same for me.
@maanas_sehgal
@maanas_sehgal 6 ай бұрын
I got a 70 line solution in java, did use like 2 sets, but got last pos on leetcode even on O(n)😢
@AKProductionsTelugu
@AKProductionsTelugu 6 ай бұрын
Unlike others but in Java i almost everytime get 0ms its sp satisfying... and you might cross check your code for unnecessary checks and iterations
@yang5843
@yang5843 6 ай бұрын
I was hoping you would make a video, thanks
@qulinxao
@qulinxao 6 ай бұрын
class Solution: def delNodes(self, r: Optional[TreeNode], t: List[int]) -> List[TreeNode]: t,o=set(t),[] def f(p): if p: p.left,p.right=f(p.left),f(p.right) if p.val not in t:return p o.extend((p.left,p.right)) o.append(f(r)) return [p for p in o if p]
@freecourseplatformenglish2829
@freecourseplatformenglish2829 6 ай бұрын
Sovled it on my own. I found these daily questions best to practise DSA questions and revise my concept.
@jokerlex6976
@jokerlex6976 6 ай бұрын
sorry for the oot, but what tools did you use when drawing the algorithm ?
@スヘア
@スヘア 6 ай бұрын
Looks like one note to me
@chien-yuyeh9386
@chien-yuyeh9386 6 ай бұрын
Nice question 🎉
@InquisitiveLittleSteps
@InquisitiveLittleSteps 6 ай бұрын
Thank you
@MP-ny3ep
@MP-ny3ep 6 ай бұрын
Great explanation as always. Thank you
@aashishbathe
@aashishbathe 6 ай бұрын
This is what I coded up. Simultaneous addition if its not to be deleted. Also didn't add everything and delete it. class Solution: def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]: to_delete = set(to_delete) roots = [] if root.val not in to_delete: roots.append(root) def dfs(node, par): nonlocal roots if node.val in to_delete: if node.left and node.left.val not in to_delete: roots.append(node.left) if node.right and node.right.val not in to_delete: roots.append(node.right) if par: if par.left and par.left.val == node.val: par.left = None else: par.right = None if node.left: dfs(node.left, node) if node.right: dfs(node.right, node) dfs(root, None) return roots
@tuandino6990
@tuandino6990 6 ай бұрын
Stack, tree and forest 🎉🎉🎉
@giovannigeorgio3032
@giovannigeorgio3032 6 ай бұрын
hey can you post the iterative solution somewhere i can do the recursive bet cant do iterative
@vikneshcs
@vikneshcs Ай бұрын
Why set is used for root storing
@samjohn5042
@samjohn5042 6 ай бұрын
Would the space complexity not be O(n+m) because of the two hashsets?
@alijohnnaqvi6383
@alijohnnaqvi6383 5 ай бұрын
Approach Beats 99% of users with Python :) Recursively go through each node in a tree If you have to delete this node from tree, add its left and right children to output as they are forest roots now If you do not have to delete the node, return it as it, because at the end we care for highest level node Complexity Time complexity: O(n) Space complexity: O(n) Code # 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: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]: output = [] to_delete = set(to_delete) def dfs(root,parent): if not root: return None left = dfs(root.left,root) right = dfs(root.right,root) if root.val in to_delete: if left is not None: output.append(left) if right is not None: output.append(right) if parent is not None: if parent.left==root: parent.left=None else: parent.right= None else: return root r = dfs(root,None) if r is not None: output.append(r) return output
@yuhangzhao3303
@yuhangzhao3303 6 ай бұрын
I am thinking if this solution misses some cases. If we have a tree like [1,2,3,4,5], to_delete is [4,5], is this solution going to work? In this case, 4 is deleted first, the child of 4(5) doesn’t have a chance to be checked? Because 4 is changed to point to None.
@DeathSugar
@DeathSugar 6 ай бұрын
Gosh I hate recursive calls. Solved with while loop using some extra space to check if node has parents (meaning is not disjointed)
@ANIMATED-ADVENTURES-p4c
@ANIMATED-ADVENTURES-p4c 6 ай бұрын
Hi, man great explanation as always ❤. I'm new to leetcode I have been solving some easy problems on my own but I can not even sometimes solve an easy problem. Sometimes I can even come up with the logic but I can not code it out. (I am using java.) Can you please guide me how can I get better at coding and finding solutions of tough problems.
@galkk3
@galkk3 6 ай бұрын
my solution, same idea but less concise: delete = set(to_delete) res = [] if root.val not in delete: res.append(root) def dfs(node, parentDeleted): if not node: return False if node.val in delete: dfs(node.left, True) dfs(node.right, True) return True if parentDeleted: res.append(node) if dfs(node.left, False): node.left = None if dfs(node.right, False): node.right = None return False dfs(root, False) return res
@playjar4854
@playjar4854 6 ай бұрын
class Solution: def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]: res=[] to_delete=set(to_delete) def dfs(root): if not root: return False result=dfs(root.left) if result: if root.left.left: res.append(root.left.left) if root.left.right: res.append(root.left.right) root.left=None result=dfs(root.right) if result: if root.right.left: res.append(root.right.left) if root.right.right: res.append(root.right.right) root.right=None if root.val in to_delete: return True return False result=dfs(root) if result: if root.left: res.append(root.left) if root.right: res.append(root.right) else: res.append(root) return res
@Yoo_broo_Jr
@Yoo_broo_Jr 6 ай бұрын
Bruhh just love your consistency in posting every solutions for the problem of the day. Keep going bruhh LOVE YOU😇🤗
@aashishbathe
@aashishbathe 6 ай бұрын
This wasn't super tough, but then had some edge cases..
@pastori2672
@pastori2672 6 ай бұрын
its so sad the only problem i missed is "maximum score from removing substring" because i misinterpreted it 😭
@tusharbhatia5437
@tusharbhatia5437 6 ай бұрын
Bro doesn't miss
@anantakarmakar3458
@anantakarmakar3458 6 ай бұрын
class Solution { public: vector res; unordered_set del; void dfs(TreeNode *&root) { if (root == NULL) return; dfs(root->left); dfs(root->right); if (del.find(root->val) != del.end()) { if (root->left) res.push_back(root->left); if (root->right) res.push_back(root->right); root = NULL; delete root; } } vector delNodes(TreeNode *root, vector &to_delete) { for (int i = 0; i < to_delete.size(); i++) { del.insert(to_delete[i]); } dfs(root); if (root) res.push_back(root); return res; } };
@stoney78us
@stoney78us 6 ай бұрын
I might be wrong but it looks like the deleted nodes are still connected to theirs children even though the result still satisfied.
@sidazhong2019
@sidazhong2019 5 ай бұрын
My code for this question is very long and ugly. As a tree problem, the code should not be so long. I just came here to confirm that this question is really that disgusting, and it seems that I was right.
@saikumaradapa3266
@saikumaradapa3266 6 ай бұрын
A simple BFS solution in your style, is it? class Solution: def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]: target = set(to_delete) if not target: return [root] res = [] if root.val not in target: res.append(root) curr = TreeNode(-1, root) q = deque([curr]) while q: node = q.popleft() if node.left: q.append(node.left) if node.left and node.left.val in target: node.left = None if node.right: q.append(node.right) if node.right and node.right.val in target: node.right = None if node.val in target: if node.left and node.left.val not in target: res.append(node.left) if node.right and node.right.val not in target: res.append(node.right) return res
@pastori2672
@pastori2672 6 ай бұрын
cute problem 🥰
@giovannigeorgio3032
@giovannigeorgio3032 6 ай бұрын
A simple recursive java solution class Solution { private List trees = new ArrayList(); private TreeNode helper(TreeNode root, Set to_delete){ if(root == null){ return null; } TreeNode leftTree = helper(root.left, to_delete); TreeNode rightTree = helper(root.right, to_delete); if(to_delete.contains(root.val)){ if(leftTree != null) trees.add(leftTree); if(rightTree != null) trees.add(rightTree); return null; } root.left = leftTree; root.right = rightTree; return root; } public List delNodes(TreeNode root, int[] to_delete) { Set del = new HashSet(); for( var i : to_delete ){ del.add(i); } TreeNode node = helper(root, del); if(node != null){ trees.add(node); } return trees; } }
@TWEEDOriginal
@TWEEDOriginal 6 ай бұрын
// My JS solution using top-down deletion and collection var delNodes = function (root, to_delete) { to_delete = new Set(to_delete) const res = [] function dfs(node, parent) { if (!node) return let newParent = null // if node is deleted then it's children has no parent if (to_delete.has(node.val)) { if (parent) { if (parent?.left?.val === node.val) parent.left = null else parent.right = null } } else { if (!parent) res.push(node) newParent = node } dfs(node.left, newParent) dfs(node.right, newParent) } dfs(root, null) return res };
@knight-uy7bp
@knight-uy7bp 6 ай бұрын
@neetcode Why is the java equivalent of the above code not working? class Solution { HashSet delSet = new HashSet(); HashSet resSet = new HashSet(); List res = new ArrayList(); // DFS , Hashset public List delNodes(TreeNode root, int[] to_delete) { for(int n: to_delete){ delSet.add(n); } dfs(root); for(TreeNode node: resSet){ res.add(node); } return res; } public TreeNode dfs(TreeNode node){ if(node == null){return null;} TreeNode res = node; if(delSet.contains(node.val)){ res = null; resSet.remove(node); if(node.left != null){ resSet.add(node.left); } if(node.right != null){ resSet.add(node.right); } } node.left = dfs(node.left); node.right = dfs(node.right); return res; } }
@chrischika7026
@chrischika7026 6 ай бұрын
what type of traversal is this @NeetCodeIO
@nirmalgurjar8181
@nirmalgurjar8181 6 ай бұрын
Post Order.
@nirmalgurjar8181
@nirmalgurjar8181 6 ай бұрын
Post Order.
1110. Delete Nodes And Return Forest | DFS | Tree
12:33
Aryan Mittal
Рет қаралды 4,4 М.
Counter-Strike 2 - Новый кс. Cтарый я
13:10
Marmok
Рет қаралды 2,8 МЛН
Jaidarman TOP / Жоғары лига-2023 / Жекпе-жек 1-ТУР / 1-топ
1:30:54
Vampire SUCKS Human Energy 🧛🏻‍♂️🪫 (ft. @StevenHe )
0:34
Alan Chikin Chow
Рет қаралды 138 МЛН
Find Eventual Safe States - Leetcode 802  - Python
13:18
NeetCodeIO
Рет қаралды 7 М.
Detonate the Maximum Bombs - Leetcode 2101 - Python
11:20
NeetCodeIO
Рет қаралды 14 М.
DELETE NODES AND RETURN FOREST | LEETCODE # 1110 | PYTHON DFS SOLUTION
15:54
Filling Bookcase Shelves - Leetcode 1105 - Python
19:17
NeetCodeIO
Рет қаралды 16 М.
Number of Good Leaf Nodes Pairs - Leetcode 1530 - Python
20:22
NeetCodeIO
Рет қаралды 12 М.
Delete Nodes and Return Forest
14:48
Kevin Naughton Jr.
Рет қаралды 31 М.
My Brain after 569 Leetcode Problems
7:50
NeetCode
Рет қаралды 2,8 МЛН