You CAN do it recursively in Python by writing a Generator function, which uses *yield* and *yield from.* The end result is a very clean in-order recursive traversal that's been consumed sequentially, but with O(h) memory ( O(1) for our own state + O(h) where Python keeps track of the generator state).
@manishk24292 жыл бұрын
Me: The perfect intro doesn't exi- NeetCode: Let's write some more NeetCode today Me: (Throws earphones in the air) THERE IT IS !!!
@carloscarrillo2012 жыл бұрын
You're a good man, NeetCode. Thanks!
@kostaad2 жыл бұрын
I wonder if a yield based solutions with co-routines will be sufficient for an interviewer.
@yashshukla1637Ай бұрын
Introduction to Problem: We are implementing a Binary Search Tree (BST) Iterator that allows in-order traversal of a BST. The iterator behaves like standard iterators in languages like Java, ensuring values are returned in sorted order. Three methods to implement: constructor, hasNext(), and next(). Basic Solution: In-order traversal stores all values in an array. hasNext() returns true if values remain, otherwise false. next() returns the next value in the array. Time complexity: O(n) for the constructor and O(1) for hasNext and next. Optimized Approach: Challenge: Reduce space complexity from O(n) to O(h) (h = tree height). New solution will ensure average O(1) time for next() and hasNext() but reduce memory usage by using the tree's structure. DFS and Tree Traversal: The problem can be solved using Depth First Search (DFS) (either recursive or iterative). Recursive DFS stores extra data that can be avoided by using an iterative DFS with a stack. Iterative In-order Traversal: Use a stack to hold nodes, allowing traversal without recursion. Only the nodes from the current traversal path are stored in the stack, keeping the memory usage O(h). Details of the Optimized Implementation: next(): Pops the top node from the stack, checks if the node has a right child, and adds all left descendants of the right child to the stack. hasNext(): Simply checks if the stack is non-empty. Implementation Insights: Memory efficiency: Nodes are pushed onto the stack only when needed (i.e., as we traverse the tree). After processing a node, its right child is explored, ensuring nodes are added in sorted order. Conclusion and Code: The stack and iterative approach guarantee O(h) space complexity. Code for next() and hasNext() is efficient, and repeating 3 lines of logic in the constructor is acceptable for simplicity. Final code successfully passes tests.
@techandmore122 ай бұрын
Here did it little different: class BSTIterator: def __init__(self, root: Optional[TreeNode]): self.root = root self.stack = [] self.cur = root def next(self) -> int: while self.stack or self.cur: while self.cur: self.stack.append(self.cur) self.cur = self.cur.left self.cur = self.stack.pop() result = self.cur.val self.cur = self.cur.right return result def hasNext(self) -> bool: return self.cur or self.stack
@7oeseven7932 ай бұрын
Is doing the inorder traversal and adding the root to a queue works too? it passes all cases on Leetcode and beats 70%. However, I just seen all the different answers and they all use a stack...nvm just seen more of the video. its too much space complexity.
@shantanukumar40812 жыл бұрын
Great Explanation !!!
@lucashowes40892 жыл бұрын
Ik google prolly pays you a bag but they might be wasting your talents. Haven't had online instruction this quality since khan academy
@ngneerin Жыл бұрын
This comment ruined his life. Now he does his thing for peanuts
@sprajosh10 ай бұрын
@@ngneerin😂😂 I think he’ll figure out what to do with his life
@eva__43806 ай бұрын
😂😂😂😂😂@@ngneerin
@bhanuvarma12395 ай бұрын
In the given question they asked that implement in the ""In-order Traversal""...But you did it in the ""pre-Order"" ##In-order traversal 1.left node 2.root node 3.right node 👉👉Please clear my doubt sir🙏🙏
@ChanChan-pg4wu2 жыл бұрын
You are always very helpful! I wish I could work with you in the future!
@techno_season_142 жыл бұрын
Omg! Thank you so much! I love your videos Neetcode! Just curious, could you also solve Perfect Rectangles?
@xjlonelystar2 жыл бұрын
Man U doing more leetcode than me and u already have a job ☠️
@essamobeid15072 жыл бұрын
amazing solution! thanks a lot for posting:)
@alexandremarangonicosta4 ай бұрын
Why space is O(h) if the first thing you do is to store the root, which contains all elements in its memory? Looks like space is also O(n). EDIT: you are actually right....the left/right of a TreeNode, in python, only hold the reference of an object, not the object directly...so it behaves like a real pointer in C.
@usmanakram51912 жыл бұрын
Does there exists a solution with O(1) space complexity for this problem?
@charleskorey65152 жыл бұрын
Yes there exists but then you have to do o(n) search everytime and it won’t be an iterator anymore. If you count recursion stack then o(1) is not possible
@ibrahimalshubaily95202 жыл бұрын
Still dont get why does has next work?
@dewangpatil49902 жыл бұрын
Hello Sir i am a big fan......I have a very important request....... Could you please make solution playlist of Striver's SDE Sheet. Its will be very beneficial for us students
@CommandantNOVA2 жыл бұрын
A lot of problems on the sheet overlap with the leetcode top 75. There's a top 75 playlist already.
@dusvn1484Ай бұрын
Ahaahahahah your first appoarch of solution is my solution and I know it's not efficient but I'm still stuct to find better solution.
@MysteriousIndiaYT2 жыл бұрын
Bro i am expert in python. But very confused, which career i have to choose for my life. Django Developer vs Data Scientist? Can anyone please guide me. I have little knowledge of both
@Ankit-hs9nb2 жыл бұрын
Be a machine learning engineer I am a Data Scientist with 4 years of experience and now switching to Machine Learning engineer
@sidazhong2019 Жыл бұрын
@@Ankit-hs9nb The Machine Learning engineer minium requirement is PHD.
@zohahs52762 жыл бұрын
how good one has to be in maths to solve these algos?
@srx2106 Жыл бұрын
for some reason the constructor keeps going over my head
@harshavardhanveerannanaval86052 жыл бұрын
Can someone please verify if it could be done this way? class BSTIterator: def __init__(self, root: Optional[TreeNode]): arr=[] def flatten(root): if(root): flatten(root.left) arr.append(root.val) flatten(root.right) flatten(root) self.arr=arr def next(self) -> int: return(self.arr.pop(0)) def hasNext(self) -> bool: return(self.arr) I just done a inorder traversal before hand and store it in an array
@sidazhong2019 Жыл бұрын
This problem is easy.
@adriandelfin80472 жыл бұрын
How do I cope with so many failures in a few months
@fawadazhermalik98852 жыл бұрын
Bro failures are an essential part of life that give us new lessons, which we don't get if we don't fail.