Sharing my Java O(1) extra space code


  • 7
    W
    public void connect(TreeLinkNode root) {
        TreeLinkNode cur;
        TreeLinkNode nextLevel = root;
        while (nextLevel != null) {
            cur = nextLevel;
            // at each level, connects the children nodes
            while (cur != null && 
                    cur.left != null // checking for leaf nodes
                    ) 
            {
                cur.left.next = cur.right;
                if (cur.next != null) {
                    cur.right.next = cur.next.left;
                }
                cur = cur.next; 
            }
            
            nextLevel = nextLevel.left;
            
        }
    }

Log in to reply
 

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