Practice › Trees
Insert into a BST
Easy · Trees · Asked at Amazon, Microsoft, TCS, Infosys, Wipro
Insert the value x into the binary search tree as a new leaf, at the place where an ordinary BST search for x ends (go left when x is smaller than the node, right when larger). x is not already in the tree. Print the resulting tree.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node. Third line: x.
Output
The tree in the same level-order format on one line (-1 for missing children, trailing -1s removed).
Constraints
- 1 ≤ number of nodes ≤ 10^4
- all values are distinct and positive
Walk down from the root choosing a side by comparison until the child on that side is missing, and attach the new node there.
Example 1
Input
5 4 2 7 1 3 5
Output
4 2 7 1 3 5
Example 2
Input
7 40 20 60 10 30 50 70 25
Output
40 20 60 10 30 50 70 -1 -1 25
Hints
- A BST search for x ends at an empty spot — that is where x belongs.
- At each node go left if x is smaller, right if larger.
Approach
Walk from the root: choose the side by comparing x with the node. When the child on that side is missing, attach a new node with x there. Nothing else in the tree moves. The walk takes O(height) steps.
Complexity: O(h) time for the insert · O(n) to read and print
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// level order with -1 for a missing child
Node *build(const vector<long long> &a) {
if (a.empty() || a[0] == -1) return nullptr;
Node *root = new Node(a[0]);
queue<Node *> q;
q.push(root);
size_t i = 1;
while (!q.empty() && i < a.size()) {
Node *cur = q.front();
q.pop();
if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
i++;
if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
i++;
}
return root;
}
vector<long long> readTree() {
int k;
cin >> k;
vector<long long> a(k);
for (auto &x : a) cin >> x;
return a;
}
string serialize(Node *root) {
vector<long long> out;
queue<Node *> q;
q.push(root);
while (!q.empty()) {
Node *n = q.front();
q.pop();
if (!n) {
out.push_back(-1);
continue;
}
out.push_back(n->val);
q.push(n->left);
q.push(n->right);
}
while (!out.empty() && out.back() == -1) out.pop_back();
string s;
for (size_t i = 0; i < out.size(); i++) s += (i ? " " : "") + to_string(out[i]);
return s;
}
int main() {
Node *root = build(readTree());
long long x;
cin >> x;
Node *n = root;
while (true) {
Node *&child = x < n->val ? n->left : n->right;
if (!child) {
child = new Node(x);
break;
}
n = child;
}
cout << serialize(root) << "\n";
return 0;
}Python solution
import sys
from collections import deque
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build(a):
"""Level order with -1 for a missing child."""
if not a or a[0] == -1:
return None
root = Node(a[0])
q = deque([root])
i = 1
while q and i < len(a):
cur = q.popleft()
if i < len(a) and a[i] != -1:
cur.left = Node(a[i])
q.append(cur.left)
i += 1
if i < len(a) and a[i] != -1:
cur.right = Node(a[i])
q.append(cur.right)
i += 1
return root
def serialize(root):
out, q = [], deque([root])
while q:
n = q.popleft()
if n is None:
out.append(-1)
continue
out.append(n.val)
q.append(n.left)
q.append(n.right)
while out and out[-1] == -1:
out.pop()
return " ".join(map(str, out))
data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = build(data[1 : 1 + k])
x = data[1 + k]
node = root
while True:
if x < node.val:
if node.left is None:
node.left = Node(x)
break
node = node.left
else:
if node.right is None:
node.right = Node(x)
break
node = node.right
print(serialize(root))Java solution
import java.io.*;
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// level order with -1 for a missing child
static Node build(long[] a) {
if (a.length == 0 || a[0] == -1) return null;
Node root = new Node(a[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < a.length) {
Node cur = q.poll();
if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
i++;
if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
i++;
}
return root;
}
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static long next() throws IOException {
in.nextToken();
return (long) in.nval;
}
static long[] readTree() throws IOException {
int k = (int) next();
long[] a = new long[k];
for (int i = 0; i < k; i++) a[i] = next();
return a;
}
static String serialize(Node root) {
ArrayList<Long> out = new ArrayList<>();
ArrayDeque<Node> q = new ArrayDeque<>();
ArrayList<Node> order = new ArrayList<>();
order.add(root);
for (int h = 0; h < order.size(); h++) {
Node n = order.get(h);
if (n == null) {
out.add(-1L);
continue;
}
out.add(n.val);
order.add(n.left);
order.add(n.right);
}
while (!out.isEmpty() && out.get(out.size() - 1) == -1) out.remove(out.size() - 1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < out.size(); i++) sb.append(i > 0 ? " " : "").append(out.get(i));
return sb.toString();
}
public static void main(String[] args) throws IOException {
Node root = build(readTree());
long x = next();
Node n = root;
while (true) {
if (x < n.val) {
if (n.left == null) {
n.left = new Node(x);
break;
}
n = n.left;
} else {
if (n.right == null) {
n.right = new Node(x);
break;
}
n = n.right;
}
}
System.out.println(serialize(root));
}
}