Simple Solution


  • 1
    public void connect(TreeLinkNode root) {
    	if(root==null) return;
    	TreeLinkNode current = root;
    	TreeLinkNode nextLevel = current.left;
    	while(current.left!=null) {
    		nextLevel = current.left;
    		while(current!=null) {
    			current.left.next=current.right;
    			if(current.next!=null) current.right.next=current.next.left;
    			current = current.next;
    		}
    		current = nextLevel;
    	}
    }
    
    1. current points to the current node on the current level
    2. nextLevel points to the first node of the next level
    3. while current!=null connect the children of the current node
    4. if current has next connect the current right children with the
      current.next left child
    5. if current has next update current to current.next
    6. when the current level has no more nodes (current==null), point
      current to the first node of the next level and restart the loop
      (current = nextLevel)

Log in to reply
 

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