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;
               firstChild= cur.left!=null? cur.left: cur.right;
               while(firstChild==null &&!=null){
                   firstChild = cur.left!=null?cur.left:cur.right;
                   second = first==cur.left?cur.right:null;
                   while(second==null &&!=null){
                       second = cur.left!=null?cur.left:cur.right;
          = second;
               cur = firstChild;

Log in to reply

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