Java Solution, time O(n), space O(1)


  • 0
    M
        public void connect(TreeLinkNode root) {
            TreeLinkNode head = root;
            while(head!=null){
                TreeLinkNode prev=  null, nextHead = null;
                TreeLinkNode cur = head;
                while(cur!=null){
                    if(cur.left != null){
                        if(prev!=null){
                            prev.next = cur.left;
                        }
                        prev = cur.left;
                        if(nextHead == null) nextHead = cur.left;
                    }
                    if(cur.right!=null){
                        if(prev!=null){
                            prev.next = cur.right;
                        }
                        prev = cur.right;
                        if(nextHead == null) nextHead = cur.right;
                    }
                    cur = cur.next;
                }
                head = nextHead;
            }
        }
    

Log in to reply
 

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