VOOZH about

URL: https://www.geeksforgeeks.org/dsa/binary-tree-to-binary-search-tree-conversion/

⇱ Binary Tree to BST Conversion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Binary Tree to BST Conversion

Last Updated : 3 May, 2026

Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. 

Examples

Input:

👁 Binary-Tree-to-Binary-Search-Tree-Conversion

Output:

👁 Binary-Tree-to-Binary-Search-Tree-Conversion-3

Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. 

Using Inorder Traversal & Sorting - O(n log n) Time and O(n) Space

Use the fact that inorder traversal of a BST is sorted. Store all node values using inorder, sort them, then refill the tree using inorder traversal so it becomes a BST without changing its structure.

  • Perform inorder traversal and store values in a vector and sort the vector
  • Traverse tree again using inorder and replace node values with sorted values using an index variable.


Below is the implementation of the above approach:


Output
2 4 7 8 10 
Comment
Article Tags: