Most clear Java Solutin


  • 0

    Our routine is to connect nodes level by level.
    For every level we do three steps:

    1. check current start is not null
    2. find the first child which is the start of next iteration
    3. connect all children
    4. point current start to first child
    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root==null) return;
    
            TreeLinkNode cur=root, first=null, second=null;
            TreeLinkNode firstChild=null;
            while(cur!=null){
               firstChild= cur.left!=null? cur.left: cur.right;
               while(firstChild==null && cur.next!=null){
                   cur=cur.next;
                   firstChild = cur.left!=null?cur.left:cur.right;
               }
               
               first=firstChild;
               while(first!=null){
                   second = first==cur.left?cur.right:null;
                   while(second==null && cur.next!=null){
                       cur=cur.next;
                       second = cur.left!=null?cur.left:cur.right;
                   }
                   first.next = second;
                   first=second;
               }
               
               cur = firstChild;
            }
        }
    }
    
    
    

Log in to reply
 

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