Simple java solution based on level order traversal


  • 2
    A
    public void connect(TreeLinkNode root) {  
    
      LinkedList<TreeLinkNode> q =new LinkedList<TreeLinkNode>();
    
      q.add(root);
      
      if(root!=null){
    
      while(q.size() > 0){
          
          int nodeCount=q.size();
          
          while(nodeCount > 0){
              
              TreeLinkNode curr=q.poll();
              
              if(nodeCount==1) 
                 curr.next=null;
              else
                 curr.next=q.peek();
                 
              if(curr.left!=null)
                 q.add(curr.left);
              if(curr.right!=null) 
                 q.add(curr.right);
                 
              nodeCount--;
          }
      }
    }
    

    }


Log in to reply
 

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