Java iterative with explanation


  • 2
    M
    1. Keep track of the left most child.

    2. Hook up the next pointers for the children of this level.

    3. Drop down into the saved left most child

    4. repeat.

       public void connect(TreeLinkNode root) {
      TreeLinkNode left = root;
      TreeLinkNode current = root;
      while(left != null){
      	left = current.left;
      	if(left==null)break;
      	while(current != null){
          	current.left.next = current.right;
          	current.right.next = current.next == null ? null : current.next.left;
          	current = current.next; 
      	}
      	current = left;
      }
      

      }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.