Java solution traversing by level without extra space


  • 24
    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root==null) return;
            TreeLinkNode cur = root;
            TreeLinkNode nextLeftmost = null;
    
            while(cur.left!=null){
                nextLeftmost = cur.left; // save the start of next level
                while(cur!=null){
                    cur.left.next=cur.right;
                    cur.right.next = cur.next==null? null : cur.next.left;
                    cur=cur.next;
                }
                cur=nextLeftmost;  // point to next level 
            }
        }
    }

Log in to reply
 

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