Thanks! If you need help with these kinds of problems be sure to sign up for the interviewing service I created! thedailybyte.dev/?ref=kevin I recommend joining the annual tier if you can!
Very helpful video, I was struggling with the explanation on leetcode. This video made it too easier to understand and that too in minimum amount of time. Thank you!
Hey man, love your videos! Just a small request, the music makes it a bit hard to concentrate esp with the high pitches.. would really appreciate if the volume was lower. Thanks again
Have been looking for the level-specific control over the BFS for a while. The trick found in this video is to iterate the level with the queue length. This trick is also useful to find the level-average of a tree (another FB question on Leet) Thanks man!!! also watched the running gurlfriend behind you in other videos :-) lol..
Always found BFS and DFS difficult to understand. Loved your video and explanation. Thanks to your video I could understand better ! Could you please explain and code the recursive version as well ?
@Kevin Naughton Jr. Before watching your video, I implemented a level-order traversal that was okay, but it put everything in just one list. But after watching your video I realised that I don't have to use just one dequeue operation for each enqueue operation. Like a lightning that struck me. And for size of current level, I was using 2^n kind of logic. but your answer simplified it very much. Thank you very much!!!
Hi Kevin , great job as usual ! just a suggestion, It would be better if a quick time/space complexity analysis is included at the end of the video! :)
Hi Kevin, in the algo you described where the processing of queue is performed, you find out the size of queue and then looped all the result, on submission output is [[3],[9,20],[15,7]]. I instead of finding out the size used while loop till its not empty and i got result [[3,9,20,15,7]]. So didn't get why it happens like this. can you help!
hey kevin ! I don't know how to get comfortable with these recursion type of problems , I mean it never happened to me that I know how to apply recursion in the right way ...help me out plz
Great solution,but I don't hear any explanation, at least not up to @5:06 of ~why~ the currentLevel contains the current-level-nodes. I did get it why.. but it wasn't said why
Life Simply Rocks anytime! If you need help with more problems like this be sure to sign up for the interviewing service I made The Daily Byte. I recommend joining a premium plan if you can! thedailybyte.dev/?ref=kevin
I'm a bit confused here. Why did you add currentLevel to the result, but in lines 26 and 29 you're adding the values to the queue. Are the queue and currentLevel list holding the same values? Hope you can clarify.
que here is to track all elements which are at same level so at each iteration queue will contain only same level elements and current level will contain all those elements
so for every iteration, or every level in the tree, you will have the correct set of elements because you popped the previous level's nodes off of the queue?
Memory usage can be improved (better than 100% of java solutions) simply by replacing the LinkedList queue with an ArrayDeque Deque: class Solution { public List levelOrder(TreeNode root) { List result = new ArrayList(); if (root == null) return result; Deque queue = new ArrayDeque(); queue.addLast(root); while (queue.size() > 0) { List currLevel = new ArrayList(); int currNumNodes = queue.size(); // number of nodes in the current level for (int i = 0; i < currNumNodes; i++) { TreeNode currNode = queue.removeFirst(); currLevel.add(currNode.val); if (currNode.left != null) queue.addLast(currNode.left); if (currNode.right != null) queue.addLast(currNode.right); } result.add(currLevel); } return result; } }
Python solution # 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: TreeNode) -> List[List[int]]: #Iterative solution using BFS. Remember, we use Queue in BFS # We are using Queue here. if root == None: return [] result = [] queue = [] #append root queue.append(root) # do while queue is empty while (queue): #size represent total nodes at that level size = len(queue) #set currentlevel to store elements of a level, reset again after for loop ends for every level currentlevel = [] #for all nodes at a level, pop a node and append it to currentlevel for i in range(size): current = queue.pop(0) currentlevel.append(current.val) #if node has left child, add it to queue if current.left: queue.append(current.left) #if node has right child, add it to queue if current.right: queue.append(current.right) #after for loop ends, append all nodes in currentlevel to our result result.append(list(currentlevel)) #return result return result
What do you think of this: var levelOrder = function(root) { let result = []; let level = 1; function traversal(node) { //3; if (node === null) { return; } if (result[level - 1] === undefined) { result[level - 1] = []; } result[level - 1].push(node.val); level++ //2; traversal(node.left); traversal(node.right); level--; } traversal(root); return result; }; The idea is just to keep level and push each node value to the specific array index, which is level - 1.
Thank you! Just checked out your channel looks like you're doing some great things keep up the good work!!! Happy to see we're both trying to help people!
Anytime! Unfortunately, I don't think I'm going to upload the same video without audio but maybe you can try watching with no sound and put on the captions? Sorry about the music, I'm still trying to decide if I should include it in the videos or not (I feel like some people might get bored just hearing my voice?). If I do decide to use music I'll try to make sure it's pretty quiet and not distracting, sorry if it bothered you!
but it's NOT !, you can do exactly the same without ever using a queue, just traverse the tree recursively, passing "depth" and a callback as a parameter, and add the values of the node to the result in the callback (an array of arrays, where the index is the depth), i don't see the need for a queue here at all
@@pizzagorgonzola Kevin's video is helpful. There are often multiple methods to solve one problem and it's a good idea to become familiar with different approaches. Each approach has its pros and cons, so try not to dismiss alternative solutions.
@@eileencrusta2448 you are wrong, while this is a long time ago, i think his method is slower, it allocates memory !, u don't need to allocate ANY memory to traverse a tree, this is a black and white issue, this is NOT the way to do this at all
@@pizzagorgonzola Yeah, I realized your original comment was from a year ago. Thanks for coming back to reply to me! (: I haven't written out the recursive algorithm as you described. However, when you're doing a level order traversal or breadth first search in a tree, I get the impression that using a queue is much more practical. A bit of memory savings isn't always the most important factor. Sometimes a solution that uses more memory makes more sense practically. If the problem wasn't specifically to return an array of values level by level, then I believe a recursive approach would make more sense. Thanks again for your input.
Hey Neal! That was actually on a separate submission previous to the video. If I remember correctly it was a small syntax error like forgetting a semicolon
Rather than writing code directly you could have explained concept on white board first and then code and also brute- > optimised approach is better...Otherwise its useless..