L8. Level Order Traversal of Binary Tree | BFS | C++ | Java

  Рет қаралды 414,201

take U forward

take U forward

Күн бұрын

Пікірлер: 301
@takeUforward
@takeUforward 3 жыл бұрын
If you understand, pleaseeeeee like and subscribeeeee :) Do follow me at Insta: striver_79
@genzsubh
@genzsubh Жыл бұрын
Nhi Samjhe to Dislike Bhi Likh Deta ..
@ajaykathwate7595
@ajaykathwate7595 Жыл бұрын
@@genzsubh Le, I disliked your comment!
@sayantaniguha8519
@sayantaniguha8519 11 ай бұрын
Why is the space complexity, O(n) & not the maximum number of nodes in any single level of the tree?
@dishikasingh235
@dishikasingh235 3 жыл бұрын
This series is a blessing for all those who find tree difficult...Please make series on every DS...Great Job!
@Mohit_Q
@Mohit_Q 9 ай бұрын
where are you working now ?
@TON-108
@TON-108 9 ай бұрын
@@Mohit_Q bss kr bhai 😂😂
@rickseth9207
@rickseth9207 8 ай бұрын
@@TON-108 kya kiya tere bhai ne?
@TON-108
@TON-108 7 ай бұрын
@@rickseth9207 Jaise koi ladki dikhi tut padte hai londe 😂😂
@rickseth9207
@rickseth9207 7 ай бұрын
@@TON-108 no actually yeh wala normal laga, mujhe pata hai inn sab videos mai bhi ladkiyon ke comments mai simps aate hai but yeh wala simp nahi tha.
@divyanshmishra5121
@divyanshmishra5121 5 ай бұрын
Recursive Solution using BFS: vector ans; void help(TreeNode *root,int depth) { if(root==NULL) { return; } if(ans.size()==depth) { ans.push_back(vector()); } ans[depth].push_back(root->val); help(root->left,depth+1); help(root->right,depth+1); } vector levelOrder(TreeNode* root) { help(root,0); return ans; }
@HomiePlaysYT
@HomiePlaysYT Жыл бұрын
Java soln using Recursion without any queue: public List levelOrder(TreeNode root) { List ans = new ArrayList(); travel(0, root, ans); return ans; } private void travel(int level, TreeNode cur, List ans) { if (cur == null) return; // add another list only when we visit a new level for the first time if (level >= ans.size()) ans.add(new ArrayList()); ans.get(level).add(cur.val); // get the list of that level add the node val to it travel(level + 1, cur.left, ans); travel(level + 1, cur.right, ans); }
@fantasyillusion
@fantasyillusion 2 жыл бұрын
For those looking for python 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ans=[] if root==None: return ans queue=deque([root]) while queue: n=len(queue) level=[] for i in range(n): node=queue.popleft() if node.left!=None: queue.append(node.left) if node.right!=None: queue.append(node.right) level.append(node.val) ans.append(level) return ans
@gunahawk6893
@gunahawk6893 2 жыл бұрын
def levelOrder(self): if self.root == None: return else: self._levelOrder(self.root) def _levelOrder(self,curNode): q = [] q.append(curNode) while len(q) != 0: curNode = q.pop(0) print(curNode.value , end= " ") if curNode.left != None: q.append(curNode.left) if curNode.right != None: q.append(curNode.right)
@Rahul_Mongia
@Rahul_Mongia 7 ай бұрын
😅
@banothutharun2743
@banothutharun2743 8 ай бұрын
what a fentastic explaination sir. simply superb
@krishnasudan3410
@krishnasudan3410 3 жыл бұрын
Just started it and loving it.. On point clear explanation.. No khich khich... No time waste.. Worth watching.. ♥️
@SB-hb2kx
@SB-hb2kx Жыл бұрын
The expaination was so good that even after 6months I was able to solve it without help. Thank you @Striver bhaiya
@PriyaGupta-sg4sm
@PriyaGupta-sg4sm 9 ай бұрын
No one has ever made level order this easy!
@susmitapatil4847
@susmitapatil4847 7 ай бұрын
He is the best tutor. Good job
@lifehustlers164
@lifehustlers164 Жыл бұрын
9/54 (16% done)!!!
@kermitdaphrogge525
@kermitdaphrogge525 2 ай бұрын
Are you now placed, brother?
@vganesh9829
@vganesh9829 8 ай бұрын
Understood Striver!😊
@cinime
@cinime 2 жыл бұрын
Understood! Super gorgeous explanation as always, thank you very much!!
@vedantsharma5876
@vedantsharma5876 3 жыл бұрын
Striver you are a boon to us Tier 3 Students :') Love you man!
@AdityaChaturvedi-2005
@AdityaChaturvedi-2005 2 ай бұрын
Not only tier 3 students bro . He is a boon for everyone learning dsa
@RitikKumar-bk6pj
@RitikKumar-bk6pj 2 жыл бұрын
Sir aap bahut bhadiya pdate ho thank u for making this series
@sukritikuila9161
@sukritikuila9161 2 жыл бұрын
Shouldn't be the Space Complexity : O(width) cause the queue can grow upto max nodes in a level ?
@manavshah7450
@manavshah7450 3 жыл бұрын
Understooooood!!! Awesome explanation. Please upload all videos by tomorrow, else after weekend u will get buzy with office :/
@PrashantSingh-jy6zp
@PrashantSingh-jy6zp 3 жыл бұрын
for best experience go to 0:41
@nawabkhan4916
@nawabkhan4916 2 жыл бұрын
great work, and have lots of sponsor ad so that you can provide great videos.
@averylazyandweirdhuman
@averylazyandweirdhuman 5 ай бұрын
I want to be hard working like you. You really live up to your channel name. ✌️
@shake-her3908
@shake-her3908 2 жыл бұрын
vector levelOrder(Node* node) { vector ans; queueq; q.push(node); while(!q.empty()){ //solving in hard way int size =q.size(); for(int i=0;ileft){ q.push(front->left); } if(front->right){ q.push(front->right); } ans.push_back(front->data); } } return ans; }
@yashshah660
@yashshah660 Жыл бұрын
I have also written the same code but I got a wrong answer on GFG
@lourduradjou182
@lourduradjou182 Жыл бұрын
superb bhai
@mayanksaurabhmayanksaurabh9271
@mayanksaurabhmayanksaurabh9271 2 жыл бұрын
very well explained. thanks a ton
@ganeshjaggineni4097
@ganeshjaggineni4097 4 ай бұрын
NICE SUPER EXCELLENT MOTIVATED
@apmotivationakashparmar722
@apmotivationakashparmar722 Ай бұрын
Thank you so much striver.
@rajeshwari.s.r9703
@rajeshwari.s.r9703 6 ай бұрын
Thanks a lot …I understood very clearly✌🏻 dsa playlist helped a lot for me 😇😊🤩
@AkshayKumar-oi2cu
@AkshayKumar-oi2cu 2 жыл бұрын
No one can teach like u ...sir
@codeman3828
@codeman3828 8 ай бұрын
Understood
@stith_pragya
@stith_pragya Жыл бұрын
Thank You So Much for this wonderful video.............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@atharvakulkarni2024
@atharvakulkarni2024 3 жыл бұрын
Tablet Lectures are much much effective..Thanks a lot !!DP SERIES PLEASE
@nikitakeshri9233
@nikitakeshri9233 5 ай бұрын
beautifully explained
@yashkhatwani3198
@yashkhatwani3198 2 жыл бұрын
love you, bless you, thank you.
@FusionArcs
@FusionArcs 2 жыл бұрын
You really are amazing at explaining things. Thanks, brother.
@deeptimayeemaharana2448
@deeptimayeemaharana2448 2 жыл бұрын
a for loop is there inside the while loop so how is the time complexity O(n)
@srirambharadwaj1937
@srirambharadwaj1937 Жыл бұрын
amazing explanation bhaiya
@bhavkushwaha
@bhavkushwaha 7 ай бұрын
Thankyou Striver, Understood!
@utsavseth6573
@utsavseth6573 Жыл бұрын
Superb Work RAJ.
@SatyamKumar-bw4vi
@SatyamKumar-bw4vi 2 жыл бұрын
Hare Krishna!
@md.imrankhan6912
@md.imrankhan6912 Жыл бұрын
Great Striver
@ram_pande8039
@ram_pande8039 3 жыл бұрын
you are doing a really great and self-less work. may you achieve all successes.
@samuelfrank1369
@samuelfrank1369 Жыл бұрын
UNDERSTOOD. THANKS A LOT
@deepikasrivastava3040
@deepikasrivastava3040 3 жыл бұрын
Thank you for the valuable and explanatory content.
@aadeshsharma0001
@aadeshsharma0001 3 жыл бұрын
Bhaiya code is really very clean
@rohitmittal514
@rohitmittal514 2 жыл бұрын
Thanks bhai bhot help milti iss course se. Keep making such videos. Aur ek request h DBMS ka course bhi daal do.
@AtharvaRao0104
@AtharvaRao0104 3 ай бұрын
A good teacher will tell why we need a queue to solve this.. here the teacher directly states to do a BFS we need a queue .. I'm sure a lot of people would not be able to explain from first principles ..
@hashcodez757
@hashcodez757 7 ай бұрын
Understood Striver!!
@jasonbrody4618
@jasonbrody4618 3 жыл бұрын
Liked. Cfbr will watch after some time
@sarangkumarsingh7901
@sarangkumarsingh7901 3 ай бұрын
Awesome................
@duckworth_lewis
@duckworth_lewis 8 ай бұрын
Thx thx thx
@parul8334
@parul8334 11 ай бұрын
understood ❤❤ love u sir 🥰🥰
@cinime
@cinime 2 жыл бұрын
Understood! Super amazing explanation as always, thank you very much!!
@shubhamgite7730
@shubhamgite7730 2 жыл бұрын
thank u so much bhayya for this very important tree series & your explanation is at next level yarr bahot Simply samzaa dete hoo..🤗🤗
@sayantaniguha8519
@sayantaniguha8519 11 ай бұрын
Why is the space complexity, O(n) & not the maximum number of nodes in any single level of the tree?
@sayantanmanna1360
@sayantanmanna1360 4 ай бұрын
i.e. O(2*d), where 2 is the branching factor and d is the max level
@hetpatel1772
@hetpatel1772 2 жыл бұрын
The Best Series on Tree
@nitantjoshi9903
@nitantjoshi9903 3 жыл бұрын
In java why we did List wrapList = new LinkedList() instead of just using List list = new ArrayList(); And yes why q.offer() instead of using q.add() ?
@nipunsinha7445
@nipunsinha7445 3 жыл бұрын
q.add() will throw an exception if an insertion fails, so you will have to wrap it in a try-catch block...q.offer() returns a boolean to indicate if insertions was successful or not. More explaination here docs.oracle.com/javase/tutorial/collections/interfaces/queue.html - Check the Queue Interface structure table on this page.
@koushikvss7638
@koushikvss7638 2 жыл бұрын
q.add() will throw an exception when there is no capacity to add more elements, whereas q.offer() will just return false.
@shashankkr1008
@shashankkr1008 2 жыл бұрын
Clearly understood and coded, Thanks bhaiya!!!
@pritishpattnaik4674
@pritishpattnaik4674 2 жыл бұрын
Beautifully explained , amazing
@premsagargupta5263
@premsagargupta5263 2 жыл бұрын
Thank you brother, learning trees from your series, very helpful :)
@Ashutosh.369
@Ashutosh.369 2 жыл бұрын
you wrote a lengthy code in java. we can use an arraylist to store the elements while traversing. here is the code how i have implemented void level_order( Node root ) { if( root == null ) return; ArrayList ans = new ArrayList(); // to store the elements Queue q = new ArrayDeque(); q.add( root ); while ( !q.isEmpty() ) { Node temp = q.poll(); if( temp.left !=null ) q.add( temp.left ); if( temp.right !=null ) q.add( temp.right ); ans.add( temp.data ); } System.out.println( ans ); } Narayan Narayan 😇😇
@Sungod.aditya
@Sungod.aditya 2 ай бұрын
the function needed to return List
@owaisch3442
@owaisch3442 2 жыл бұрын
is it possible to find the level of a node using preorder traversal?
@eiji11282
@eiji11282 5 ай бұрын
Sir why do we not using single vector and why do we use vector of vector???
@Tbm4545
@Tbm4545 8 күн бұрын
Is the levels needed ?? Or we can simply use a stack and print by sequnce.
@krentwhite2668
@krentwhite2668 3 жыл бұрын
This video is used to solve Zigzag Level Order traversal also... Thanks Mr. Striver👏
@DeadPoolx1712
@DeadPoolx1712 Ай бұрын
UNDERSTOOD;
@shubamgoswami
@shubamgoswami 3 жыл бұрын
THAK GYA HU VROOO RELEVEL SUN SUN KE
@AyushGupta-kp9xf
@AyushGupta-kp9xf 3 жыл бұрын
Complexity analysis at 7:36
@Mr.Indianwxvhehsy9191hghgx
@Mr.Indianwxvhehsy9191hghgx 11 ай бұрын
nice video sir
@sayankarmakar13
@sayankarmakar13 2 жыл бұрын
Thanks bhaiya for great explanation
@ajaybachate7137
@ajaybachate7137 2 жыл бұрын
if queue has n nodes inside it and we traverse for n nodes to put into vector then wont it be O(N^2) time complexity?
@mriduljain1981
@mriduljain1981 Жыл бұрын
completed lecture 8 of tree playlist.
@debugagrawal
@debugagrawal 2 жыл бұрын
Bhaiya ap abhi 1 hi approach bata rahe ho, Recusrion se bhi mast hota hai, so as per interview point of view both approaches batao, better for all students, thanks in advance ♥
@LearnWithMe7777
@LearnWithMe7777 5 ай бұрын
Understood❤
@Ramu9119
@Ramu9119 11 ай бұрын
Nice Video Brother Keep it up
@runtime379
@runtime379 3 жыл бұрын
awsome lectures
@72nishantwadhawan5
@72nishantwadhawan5 Жыл бұрын
Best Content on the internet.
@rahulyadav8159
@rahulyadav8159 Жыл бұрын
variable levelNum is quite confusing in JAVA implementation.
@asthapandey9587
@asthapandey9587 Жыл бұрын
Couldn't understand Java code
@wribo5433
@wribo5433 3 жыл бұрын
You are amazing brother! Thank you for all the hard work you put for us
@shivanisinha7035
@shivanisinha7035 2 жыл бұрын
Such an amazing video
@divyanshuyadav5524
@divyanshuyadav5524 2 жыл бұрын
While declaring Queue...What is significance of * in ?? Why can"t be it only ??
@hakunamatata-nl4js
@hakunamatata-nl4js 6 ай бұрын
Thank you
@JohnWickea
@JohnWickea 8 ай бұрын
Thanks a lot
@nagavedareddy5891
@nagavedareddy5891 2 жыл бұрын
Huge respect..❤👏
@Versha_arya
@Versha_arya 2 ай бұрын
Thank you ao muchh
@adebisisheriff159
@adebisisheriff159 10 ай бұрын
Understood!!!
@NoxuzBlog
@NoxuzBlog 2 жыл бұрын
thank you for the video
@yatharthahuja1635
@yatharthahuja1635 2 жыл бұрын
amazing content😀
@Ammaradreamart
@Ammaradreamart Жыл бұрын
Best lecture
@s_sattu_s
@s_sattu_s Ай бұрын
is it a queue or stack? because the design looks similar to stack rather than queue
@shrishshrivastava4444
@shrishshrivastava4444 Жыл бұрын
Clarity 🔥🔥
@gandhijainamgunvantkumar6783
@gandhijainamgunvantkumar6783 2 жыл бұрын
Amazing video bhaiya :)
@103himajapoluri6
@103himajapoluri6 Жыл бұрын
is bfs same as level order traversal
@willturner3440
@willturner3440 3 жыл бұрын
why space complexity should not be O(width of tree) ?
@singhs_aniket
@singhs_aniket 3 жыл бұрын
Understood 👌👌
@Code_Solver
@Code_Solver 3 жыл бұрын
Thank you Striver bayya
@DhruvSharma-mh5vf
@DhruvSharma-mh5vf 2 жыл бұрын
Well explained 👊
@elements8630
@elements8630 3 жыл бұрын
Best video I could find!!! Great job, keep up the good work bhaiya :-)
@ankitdubey9310
@ankitdubey9310 3 жыл бұрын
@take U forward striver bhaiya ye question tha ki : recursion and backtracking mein jab aap sochte ho koi sawal karne ke liye to aap kya ek cycle pura imagine karte ho? ya fir thoughtprocess kaise hota hai, mujhe approach samajh mein aa jati hai recursion and backtrack questions mein par likha nahi aata , please guide me
@gouravupadhyay9092
@gouravupadhyay9092 3 жыл бұрын
same question bro
@OtakuRiku
@OtakuRiku 3 жыл бұрын
Watch permutation and combination using backtracking... Most of the backtracking problem are based on that problem...
@pranav288
@pranav288 2 жыл бұрын
recursive leap of faith L bhai
@MrMaharaj
@MrMaharaj 2 жыл бұрын
Level Order Traversal Approach in C++: int maxDepth(TreeNode* root) { if(root == NULL) return 0; vector answer; queue q; q.push(root); while(!q.empty()) { int size = q.size(); vector level; for(int i=0;ileft != NULL) q.push(currentNode->left); if(currentNode->right != NULL) q.push(currentNode->right); level.push_back(currentNode->val); } answer.push_back(level); } return answer.size(); }
@Pritamdaspk
@Pritamdaspk 2 жыл бұрын
It's the approach of finding the maximum depth of the tree.
@ujjalbanerjee4372
@ujjalbanerjee4372 Жыл бұрын
@@Pritamdaspk only the list line is different r8?
@AB-iv4bq
@AB-iv4bq Жыл бұрын
what is val??
@laveshchanchawat6983
@laveshchanchawat6983 2 жыл бұрын
int size = queue.size(); if we remove this line and directly use for(int i = 0; i < queue.size(); i++) why the output are different?
@petermj2804
@petermj2804 2 жыл бұрын
because queue size will keep changing after popping each element,instead if we initialize the size before any of the elements are popped we don't have to worry about the queue size changing after each pop operation.
@apoorvkumar1748
@apoorvkumar1748 3 жыл бұрын
Thank You So Much!
@studynewthings1727
@studynewthings1727 7 ай бұрын
understood
L9. Iterative Preorder Traversal in Binary Tree | C++ | Java | Stack
6:50
МЕНЯ УКУСИЛ ПАУК #shorts
00:23
Паша Осадчий
Рет қаралды 5 МЛН
Муж внезапно вернулся домой @Oscar_elteacher
00:43
История одного вокалиста
Рет қаралды 6 МЛН
L14. Maximum Depth in Binary Tree | Height of Binary Tree | C++ | Java
8:05
Premature Optimization
12:39
CodeAesthetic
Рет қаралды 834 М.
The Last Algorithms Course You'll Need by ThePrimeagen | Preview
16:44
Frontend Masters
Рет қаралды 325 М.
Binary Search Algorithm in C#
17:06
Milan Jovanović
Рет қаралды 7 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 438 М.
3 Types of Algorithms Every Programmer Needs to Know
13:12
ForrestKnight
Рет қаралды 500 М.
L10. iterative Inorder Traversal in Binary Tree | C++ | Java | Stack
11:14
Fastest Way to Learn ANY Programming Language: 80-20 rule
8:24
Sahil & Sarra
Рет қаралды 915 М.