Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python

  Рет қаралды 21,390

NeetCodeIO

NeetCodeIO

Күн бұрын

Пікірлер: 16
@NeetCodeIO
@NeetCodeIO Жыл бұрын
If you're looking for today's daily LC (Can Place Flowers) -> kzbin.info/www/bejne/kHjboqSgoc-ji6s
@victoriatfarrell
@victoriatfarrell Жыл бұрын
For me I think I prefer to append right and left to the stack and just loop while the stack is non-empty, starting by placing the root in the stack before the while loop. Makes it a very clean solution.
@servantofthelord8147
@servantofthelord8147 4 ай бұрын
I was wondering why he didn't do it that way. It was cool to learn another way though.
@RakimMiddya
@RakimMiddya 2 ай бұрын
How does this work?
@akhileshgotmare9812
@akhileshgotmare9812 2 ай бұрын
@@RakimMiddya here is the code I think @victoriatfarrell is referring to def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if not root: return [] result = [] stack = [root] while stack: cur = stack.pop() result.append(cur.val) # Append right first, so that left is processed first if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) return result
@aadill77
@aadill77 Ай бұрын
Exactly I did the same.
@cyclone760
@cyclone760 Жыл бұрын
I have never thought of the call stack in this way before... great video
@saraahmed408
@saraahmed408 5 ай бұрын
Thank you so much for the explanation. But why the time complexity will be O(log n) if the tree was a balanced binary tree?
@ashok2089
@ashok2089 4 ай бұрын
It's not the Time Complexity, It's the space complexity he mentioned. So TC is O(n) as we must visit each node. SC is O(h), h is the height of the binary tree, and in the worst case SC could be O(n), in the case of a skewed binary tree. for balanced binary tree SC: O(log n).
@gsivanithin
@gsivanithin Жыл бұрын
Great explanation! nice
@theboss-zk4wx
@theboss-zk4wx Жыл бұрын
thank you!
@gsivanithin
@gsivanithin Жыл бұрын
Easy to understand
@alexandersmirnov4274
@alexandersmirnov4274 Жыл бұрын
hi Why did you decide to open a new channel? Where should we expect new videos?
@chandankhuntia7017
@chandankhuntia7017 Жыл бұрын
💞
@AbhishekAbhishek-dk2pi
@AbhishekAbhishek-dk2pi 2 ай бұрын
Its getting errors 🤦
Concatenation of Array - Leetcode 1929 - Python
4:00
NeetCodeIO
Рет қаралды 38 М.
Ozoda - Alamlar (Official Video 2023)
6:22
Ozoda Official
Рет қаралды 10 МЛН
Who is More Stupid? #tiktok #sigmagirl #funny
0:27
CRAZY GREAPA
Рет қаралды 10 МЛН
Unique Binary Search Trees II - Leetcode 95 - Python
12:51
NeetCodeIO
Рет қаралды 19 М.
L9. Iterative Preorder Traversal in Binary Tree | C++ | Java | Stack
6:50
Find Duplicate Subtrees - Leetcode 652 - Python
14:33
NeetCodeIO
Рет қаралды 20 М.
L5. Preorder Traversal of Binary Tree | C++ | Java | Code Explanation
7:29