Convert Binary Search Tree to Sorted Doubly Linked List

medium tree dfs linked list

Problem

Convert a Binary Search Tree to a sorted circular doubly-linked list in place — the left pointer becomes prev and the right pointer becomes next.

Inputroot = [4,2,5,1,3]
Output1↔2↔3↔4↔5↔1
In-order traversal: 1,2,3,4,5 — links each to the next and wraps tail↔head.

def tree_to_doubly_list(root):
    if not root: return None
    first = last = None
    def inorder(node):
        nonlocal first, last
        if not node: return
        inorder(node.left)
        if last: last.right = node; node.left = last
        else: first = node
        last = node
        inorder(node.right)
    inorder(root)
    first.left = last; last.right = first
    return first
function treeToDoublyList(root) {
  if (!root) return null;
  let first = null, last = null;
  function inorder(node) {
    if (!node) return;
    inorder(node.left);
    if (last) { last.right = node; node.left = last; } else first = node;
    last = node;
    inorder(node.right);
  }
  inorder(root);
  first.left = last; last.right = first;
  return first;
}
class Solution {
    Node first, last;
    public Node treeToDoublyList(Node root) {
        if (root == null) return null;
        inorder(root);
        first.left = last; last.right = first;
        return first;
    }
    void inorder(Node node) {
        if (node == null) return;
        inorder(node.left);
        if (last != null) { last.right = node; node.left = last; } else first = node;
        last = node;
        inorder(node.right);
    }
}
class Solution {
    Node *first = nullptr, *last = nullptr;
    void inorder(Node* node) {
        if (!node) return;
        inorder(node->left);
        if (last) { last->right = node; node->left = last; } else first = node;
        last = node;
        inorder(node->right);
    }
public:
    Node* treeToDoublyList(Node* root) {
        if (!root) return nullptr;
        inorder(root);
        first->left = last; last->right = first;
        return first;
    }
};
Time: O(n) Space: O(h)