Binary Search Tree Iterator - Leetcode 173 - Python

  Рет қаралды 42,816

NeetCode

NeetCode

Күн бұрын

Пікірлер: 38
@lakshyasaharan5348
@lakshyasaharan5348 2 жыл бұрын
Your voice so soothing and smooth.
@numberonep5404
@numberonep5404 2 жыл бұрын
ikr!!!!!!!
@calebi23
@calebi23 2 жыл бұрын
Exactly!
@DavidDLee
@DavidDLee Жыл бұрын
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).
@manishk2429
@manishk2429 2 жыл бұрын
Me: The perfect intro doesn't exi- NeetCode: Let's write some more NeetCode today Me: (Throws earphones in the air) THERE IT IS !!!
@carloscarrillo201
@carloscarrillo201 2 жыл бұрын
You're a good man, NeetCode. Thanks!
@kostaad
@kostaad 2 жыл бұрын
I wonder if a yield based solutions with co-routines will be sufficient for an interviewer.
@yashshukla1637
@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.
@techandmore12
@techandmore12 2 ай бұрын
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
@7oeseven793
@7oeseven793 2 ай бұрын
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.
@shantanukumar4081
@shantanukumar4081 2 жыл бұрын
Great Explanation !!!
@lucashowes4089
@lucashowes4089 2 жыл бұрын
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
@ngneerin Жыл бұрын
This comment ruined his life. Now he does his thing for peanuts
@sprajosh
@sprajosh 10 ай бұрын
@@ngneerin😂😂 I think he’ll figure out what to do with his life
@eva__4380
@eva__4380 6 ай бұрын
😂😂😂😂😂​@@ngneerin
@bhanuvarma1239
@bhanuvarma1239 5 ай бұрын
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-pg4wu
@ChanChan-pg4wu 2 жыл бұрын
You are always very helpful! I wish I could work with you in the future!
@techno_season_14
@techno_season_14 2 жыл бұрын
Omg! Thank you so much! I love your videos Neetcode! Just curious, could you also solve Perfect Rectangles?
@xjlonelystar
@xjlonelystar 2 жыл бұрын
Man U doing more leetcode than me and u already have a job ☠️
@essamobeid1507
@essamobeid1507 2 жыл бұрын
amazing solution! thanks a lot for posting:)
@alexandremarangonicosta
@alexandremarangonicosta 4 ай бұрын
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.
@usmanakram5191
@usmanakram5191 2 жыл бұрын
Does there exists a solution with O(1) space complexity for this problem?
@charleskorey6515
@charleskorey6515 2 жыл бұрын
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
@ibrahimalshubaily9520
@ibrahimalshubaily9520 2 жыл бұрын
Still dont get why does has next work?
@dewangpatil4990
@dewangpatil4990 2 жыл бұрын
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
@CommandantNOVA
@CommandantNOVA 2 жыл бұрын
A lot of problems on the sheet overlap with the leetcode top 75. There's a top 75 playlist already.
@dusvn1484
@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.
@MysteriousIndiaYT
@MysteriousIndiaYT 2 жыл бұрын
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-hs9nb
@Ankit-hs9nb 2 жыл бұрын
Be a machine learning engineer I am a Data Scientist with 4 years of experience and now switching to Machine Learning engineer
@sidazhong2019
@sidazhong2019 Жыл бұрын
@@Ankit-hs9nb The Machine Learning engineer minium requirement is PHD.
@zohahs5276
@zohahs5276 2 жыл бұрын
how good one has to be in maths to solve these algos?
@srx2106
@srx2106 Жыл бұрын
for some reason the constructor keeps going over my head
@harshavardhanveerannanaval8605
@harshavardhanveerannanaval8605 2 жыл бұрын
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
@sidazhong2019 Жыл бұрын
This problem is easy.
@adriandelfin8047
@adriandelfin8047 2 жыл бұрын
How do I cope with so many failures in a few months
@fawadazhermalik9885
@fawadazhermalik9885 2 жыл бұрын
Bro failures are an essential part of life that give us new lessons, which we don't get if we don't fail.
Minimum Height Trees - Leetcode 310 - Python
23:30
NeetCodeIO
Рет қаралды 21 М.
24 Часа в БОУЛИНГЕ !
27:03
A4
Рет қаралды 7 МЛН
Stop using std::vector wrong
23:14
The Cherno
Рет қаралды 148 М.
Distribute Coins in Binary Tree - Leetcode 979 - Python
17:41
NeetCodeIO
Рет қаралды 17 М.
L50. Binary Search Tree Iterator | BST | O(H) Space
14:00
take U forward
Рет қаралды 149 М.
CLOSEST BINARY SEARCH TREE VALUE II | LEETCODE # 272 | PYTHON SOLUTION
14:16
Top 7 Algorithms for Coding Interviews Explained SIMPLY
21:22
Codebagel
Рет қаралды 441 М.
CONSTRUCT BINARY TREE FROM STRING | LEETCODE 536 | PYTHON STACK SOLUTION
16:42
I Solved 100 LeetCode Problems
13:11
Green Code
Рет қаралды 244 М.
Subtree of Another Tree - Leetcode 572 - Python
14:15
NeetCode
Рет қаралды 170 М.
Американцы красят асфальт?
0:27
BAZAR CLUB
Рет қаралды 188 М.
для всей семьи
0:56
Стакановец
Рет қаралды 191 М.
НЕ ДАМ ЕЁ В ОБИДУ😡 #shorts
0:24
Паша Осадчий
Рет қаралды 1,6 МЛН