Convert Binary tree into BST
Pattern: Validate BST
Keep the shape and change only the values. A BST of this shape holds its sorted values in inorder, so collect the values, sort them, and write them back with a second inorder walk.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Change the values of a binary tree (not its shape) so that it becomes a BST holding the same values. The function returns
nothing; the tests print the tree. [10, 2, 7, 8, 4] becomes [8, 4, 10, 2, 7]. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Which traversal of a BST is sorted?
- Does the shape restrict which values go where?
- So how many BSTs of this shape hold these values?
Hints
Brute force, and why it fails
Insert all values into a new BST: a different shape, which is not what is asked.
The key insight
Inorder positions are fixed by the shape, and a BST needs them sorted, so writing the sorted values in inorder is the only answer.
Dry run
| inorder | 8 2 4 10 7 |
|---|
Tree [10, 2, 7, 8, 4]. Inorder visits 8, 2, 4, 10, 7.
The plan
values = sorted(inorder values)
walk inorder again, writing values in order
Complexity
- Time
O(n log n)- Space
O(n)
Sorting dominates.
Edge cases
- Already a BST: unchanged.
- One node.
- Empty tree.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public void binaryTreeToBST(TreeNode root) {
List<Integer> values = new ArrayList<>();
collect(root, values);
Collections.sort(values); // a BST of this shape holds the sorted values in inorder
int[] next = {0};
write(root, values, next);
}
private void collect(TreeNode n, List<Integer> out) {
if (n == null) return;
collect(n.left, out);
out.add(n.val);
collect(n.right, out);
}
private void write(TreeNode n, List<Integer> values, int[] next) { // inorder again, writing sorted values
if (n == null) return;
write(n.left, values, next);
n.val = values.get(next[0]++);
write(n.right, values, next);
}
}C++
class Solution {
public:
void binaryTreeToBST(TreeNode* root) {
vector<int> values;
collect(root, values);
sort(values.begin(), values.end()); // a BST of this shape holds the sorted values in inorder
size_t next = 0;
write(root, values, next);
}
void collect(TreeNode* n, vector<int>& out) {
if (n == NULL) return;
collect(n->left, out);
out.push_back(n->val);
collect(n->right, out);
}
void write(TreeNode* n, const vector<int>& values, size_t& next) { // inorder again, writing sorted values
if (n == NULL) return;
write(n->left, values, next);
n->val = values[next++];
write(n->right, values, next);
}
};Python
class Solution:
def binaryTreeToBST(self, root) -> None:
nodes = []
def collect(n):
if n:
collect(n.left)
nodes.append(n)
collect(n.right)
collect(root)
for n, v in zip(nodes, sorted(n.val for n in nodes)): # the sorted values, placed in inorder
n.val = vCommon mistakes
- Writing sorted values in level order.
- Building a new tree with a different shape.