Convert Binary Tree to Binary Search Tree

viaGlassdoor

Problem: Given a Binary Tree (not necessarily a BST), convert it into a Binary Search Tree while preserving the original tree's shape/structure.

Constraints: All node values are typically assumed distinct; up to 10^4 nodes.

Example: Input tree shape with values [10,2,7] preserved structurally, output rearranged so an in-order traversal yields sorted values, e.g., [2,7,10] placed into the same node positions.

Approach: Perform an in-order traversal of the original tree to collect all node values into an array, sort the array, then perform another in-order traversal of the tree, this time overwriting each visited node's value with the next value from the sorted array in order. Since in-order traversal of a BST visits nodes in ascending order, re-assigning sorted values via in-order traversal guarantees the BST property while keeping the original tree shape. Runs in O(n log n) due to the sort, O(n) traversal.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account