Back to track
#30 Medium Intermediate

BST Insert

Open the editor

Problem

Insert a value into a BST.

Constraints

1 <= N <= 200000

Hints

  1. 1

    Go left/right

  2. 2

    Recursive or iterative

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <bits/stdc++.h>
using namespace std;

struct Node { int val; Node* left; Node* right; Node(int v) : val(v), left(nullptr), right(nullptr) {} };

Node* insertNode(Node* root, int x) {
  if (!root) return new Node(x);
  if (x < root->val) root->left = insertNode(root->left, x);
  else if (x > root->val) root->right = insertNode(root->right, x);
  return root;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  // TODO: build BST and insert
  return 0;
}

© 2026 ChitChat