KatInterview

758. Convert Binary Search Tree to Sorted Doubly Linked List

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to convert a Binary Search Tree (BST) into a sorted Circular Doubly-Linked List. The conversion must be done in-place, meaning we should reuse the tree's Node objects. The left pointer of a node should point to its predecessor in the sorted list, and the right pointer to its successor. The list must be circular, meaning the last element's successor is the first element, and the first element's predecessor is the last. We need to return the head of the list, which is the node with the smallest value.

Solution

Convert Binary Search Tree to Sorted Doubly Linked List in Python

"""
# Definition for a Node.
class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
"""

class Solution:
    def treeToDoublyList(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return None
        
        self.head = None
        self.prev = None
        
        self.inorder(root)
        
        # After the traversal, self.head is the first node and self.prev is the last.
        # Connect them to make the list circular.
        self.head.left = self.prev
        self.prev.right = self.head
        
        return self.head

    def inorder(self, node: 'Optional[Node]') -> None:
        if not node:
            return
        
        # Traverse left subtree
        self.inorder(node.left)
        
        # Process current node
        if self.prev:
            # Link the previous node with the current node
            self.prev.right = node
            node.left = self.prev
        else:
            # This is the first node (smallest element)
            self.head = node
        # Update prev to current node
        self.prev = node
        
        # Traverse right subtree
        self.inorder(node.right)

Convert Binary Search Tree to Sorted Doubly Linked List in Java

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/

class Solution {
    // To keep track of the first and last visited nodes
    Node head = null;
    Node prev = null;

    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return null;
        }

        // Perform in-order traversal to link the nodes
        inorder(root);
        
        // After the traversal, `head` is the first node and `prev` is the last.
        // Connect them to make the list circular.
        head.left = prev;
        prev.right = head;
        
        return head;
    }

    private void inorder(Node node) {
        if (node == null) {
            return;
        }
        
        // Traverse the left subtree
        inorder(node.left);
        
        // Process the current node
        if (prev == null) {
            // This is the first node we are visiting (smallest element)
            head = node;
        } else {
            // Link the previous node with the current node
            prev.right = node;
            node.left = prev;
        }
        // Update `prev` to the current node for the next step
        prev = node;
        
        // Traverse the right subtree
        inorder(node.right);
    }
}

Convert Binary Search Tree to Sorted Doubly Linked List in C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/

class Solution {
private:
    Node* head = nullptr;
    Node* prev = nullptr;

    void inorder(Node* node) {
        if (!node) {
            return;
        }
        // Traverse the left subtree first
        inorder(node->left);

        // Process the current node
        if (prev) {
            // If prev is not null, link prev and current node
            prev->right = node;
            node->left = prev;
        } else {
            // If prev is null, this is the first node, so it's the head
            head = node;
        }
        // Update prev to the current node
        prev = node;

        // Traverse the right subtree
        inorder(node->right);
    }

public:
    Node* treeToDoublyList(Node* root) {
        if (!root) {
            return nullptr;
        }
        
        inorder(root);
        
        // After inorder traversal, `head` is the first node and `prev` is the last node.
        // Connect them to make the list circular.
        head->left = prev;
        prev->right = head;
        
        return head;
    }
};

Convert Binary Search Tree to Sorted Doubly Linked List in TypeScript

/**
 * Definition for _Node.
 * class _Node {
 *     val: number
 *     left: _Node | null
 *     right: _Node | null
 *     
 *     constructor(val?: number, left?: _Node | null, right?: _Node | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function treeToDoublyList(root: _Node | null): _Node | null {
    if (!root) {
        return null;
    }

    let head: _Node | null = null;
    let prev: _Node | null = null;

    const inorder = (node: _Node | null) => {
        if (node === null) {
            return;
        }

        // Traverse the left subtree
        inorder(node.left);

        // Process the current node
        if (prev === null) {
            // This is the first node (smallest element).
            head = node;
        } else {
            // Link the previous node with the current node
            prev.right = node;
            node.left = prev;
        }
        // Update prev to the current node for the next step.
        prev = node;

        // Traverse the right subtree
        inorder(node.right);
    };

    inorder(root);

    // After the traversal, `head` points to the first node and `prev` points to the last node.
    // We need to connect them to make the list circular.
    if (head && prev) {
        head.left = prev;
        prev.right = head;
    }

    return head;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.