A simple elegant iterative Java solution


  • 0
    B
    public void connect(TreeLinkNode root) {
        while(root != null && root.left != null) {
            TreeLinkNode cur = root; 
            while(cur != null) {
                cur.left.next = cur.right;
                cur.right.next = cur.next == null? null: cur.next.left;
                cur = cur.next;
            }
            root = root.left;
        }
    }
    

    Using iterative way, the space complexity can be O(1)


Log in to reply
 

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