Thanks for this, great solution. Other videos on here were 17 minutes long for some reason. It's nice to get an explanation that is straight forward and clean looking
@ChanChan-pg4wu2 жыл бұрын
good explanation, the best found on this problem! Thanks, Eric!
@linjiafu85462 жыл бұрын
how you just got 5k subscription? the most clear explanation I've ever seen!
@fireflyeeeee29802 жыл бұрын
How can dummy.next point to next level? We are changing temp.next right? Could you explain?
@EricProgramming2 жыл бұрын
How can dummy.next point to next level? Ans: Remember that head is always pointing to the parent level and the dummy and temp are always pointing to the children level. Once we connect the children level together using dummy and temp pointers, the next level that we want to traverse is the children's children, right? So we need to move our parent point one level down. That's why dummy.next is to give us the new parent node. Got it?
@fireflyeeeee29802 жыл бұрын
@@EricProgramming oh it makes sense now. Couldn't figure out for god's sake, lol. Thank you!
@praveen31232 жыл бұрын
great solution.. since you just created dummy node, how it points to the first element of next level.. i.e how dummy.next is pointing to the left of the root or start of the next level... is it because of temp node?
@revanthkovuri86602 жыл бұрын
@preveen Yes, the temp has the reference of dummy, where dummy.next points to the first Node of that level
@MeetManga2 жыл бұрын
If this problem can use extra space then we can write like that: FYI public Node connect(Node root) { Node head = root; if(root == null){ return null; } Queue queue = new LinkedList(); queue.offer(root); while(!queue.isEmpty()){ int size = queue.size(); for(int i = 0; i < size; i++){ Node node = queue.poll(); if(i < size - 1){ node.next = queue.peek(); } if(node.left != null){ queue.offer(node.left); } if(node.right != null){ queue.offer(node.right); } } } return root; }
@challengeyourmind39373 жыл бұрын
Two while loops not necessary.
@EricProgramming3 жыл бұрын
But it doesn't hurt the complexity though, what better solution do you have in mind?
@PrashantKumar-mp5zu3 жыл бұрын
@@EricProgramming For starting from next level shouldnt it be head=dummy.left
@EricProgramming2 жыл бұрын
@@PrashantKumar-mp5zu Nah, dummy node is just a dummy node, it is there to help us connect each level node's next pointer, so dummy.left and dummy.right is always null. So the correct answer here should be head = dummy.next.