Java Solution parses the whole tree twice O(n)


  • 0
    M

    Am pretty sure that this can be made better. Any suggestions?

    public class Solution {
        public void connect(TreeLinkNode root) {
            TreeLinkNode level=root;
            while(level!=null){
                TreeLinkNode lv=level;
                TreeLinkNode cur=level.left;
                if(level.left==null) cur=level.right;
                while(cur!=null && level!=null){
                    if(level.left!=null && level.left!=cur){
                        cur.next=level.left;
                        cur=cur.next;
                    }
                    else if(level.right!=cur && level.right!=null){
                        cur.next=level.right;
                        cur=cur.next;
                        level=level.next;
                    }else{
                        level=level.next;
                    }
                    //cur=cur.next;
                }
                if(lv.left!=null)level=lv.left;
                else if(lv.right!=null)level=lv.right;
                else if(lv.next!=null)level=lv.next;
                else break;
            }
            
        }
    }
    

Log in to reply
 

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