How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Converting a binary tree to a binary search tree (BST) is a classic problem in computer science that tests one's understanding of tree traversal, data reorganization, and in-place transformations. A binary tree is a structure where each node has at most two children, but the nodes are not in any specific order. In contrast, a binary search tree is a binary tree with an in-order sequence of elements, where the left child is less than the parent node, and the right child is greater than the parent node.
This article provides a detailed technical explanation on how to convert a binary tree to a BST in-place, without using any extra space for storage such as arrays or other data structures beyond the stack space used by recursive functions.
Key Steps and Concepts
In-Order Traversal
Understanding in-order traversal is crucial since it yields nodes in a sorted order for a BST. For any binary tree:
- Traverse the left subtree.
- Visit the root node.
- Traverse the right subtree.
Generating Sorted Data
Perform an in-order traversal of the binary tree to capture the data in a sorted order. Convert this sorted data back into an in-order traversal of the original tree structure.
In-Place Conversion Process
The conversion involves three major steps:
- Extract Elements using In-Order Traversal:
This step involves collecting all the elements of the binary tree in a sorted order using in-order traversal. Because we aim to achieve this without additional space, we'll need to adjust the data directly within the nodes during subsequent traversals. - Sort Data In-Place:
While sorted extraction typically uses extra space, this method entails repeated in-place traversals until all nodes are correctly placed as per BST properties. - Overwrite Nodes during Re-Traversal:
Conduct another in-order traversal, overwriting existing node values with the sorted values while the data resides within the binary tree structure.
Implementation
Below is a recursive implementation in Python. Notice how it avoids the use of extra space apart from recursion stack space:
- Recursion Stack Space: Although we aim to avoid extra space, the recursion depth uses a stack that could impact space specifically for tall trees. In real implementations, tail-call optimizations or iterative solutions with a manual stack are alternatives.
- Tree Properties: Ensure binary tree nodes do not contain cycles, as these could cause the algorithm to loop indefinitely.
- Edge Cases: Properly handle cases like empty trees or single-node trees, where vector traversal and in-place modifications are trivial.

