Straight forward Java Solution


  • 1
    public void connect(TreeLinkNode root) {
            TreeLinkNode cur = root;
            while(cur!=null){
                // find nextLeftMost node
                TreeLinkNode nextLeftMost = null;
                while(cur!=null && nextLeftMost==null){
                    nextLeftMost = cur.left!=null? cur.left: cur.right;
                    if(nextLeftMost==null)
                        cur=cur.next;
                }
                if(nextLeftMost==null)
                    return;
                
                
                // link children
                TreeLinkNode first = nextLeftMost;
                
                while(first!=null){
                    TreeLinkNode second = null;
                    if(first==cur.left) second=cur.right;
                    while(cur!=null && second==null){
                        cur=cur.next;
                        if(cur!=null)
                            second = cur.left!=null? cur.left: cur.right;
                    }
                    first.next=second;
                    first=second;
                }
                
                // point to next level
                cur = nextLeftMost;
            }
        }

Log in to reply
 

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