426. Convert Binary Search Tree to Sorted Doubly Linked List

/**

 * 426. Convert Binary Search Tree to Sorted Doubly Linked List

 * Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.

 * You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.

 *

 * We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor.

 * You should return the pointer to the smallest element of the linked list.

 */

See the solution at github here: https://github.com/zcoderz/leetcode/blob/main/src/main/java/recursion/ConvertBSTtoSortedDoubleLinkedList.java

Observation: We need to process the tree in order so that we can create a sorted linked list. While traversing we need to keep pointer to head and previous node around. Previous node so that we can connect next node to the prior and vice versa. Head so that we can connect last node to it and return it. Traversal is straight forward, recurse left, create node and set pointers, and then recurse right.

Here is the code:

void inOrderTraversal(TreeNode node) {
    if (node == null) {
        return;
    }
    inOrderTraversal(node.left);
    if (head == null) {
        head = new TreeNode(node.val);
        prior = head;
    } else {
        TreeNode curr = new TreeNode(node.val);
        prior.right = curr;
        curr.left = prior;
        prior = curr;
    }
    inOrderTraversal(node.right);
}