← Home

701. Insert into a Binary Search Tree

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
701

Let's make this one less mysterious. For 701. Insert into a Binary Search Tree, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are insertIntoBST.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
03
04Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
05
06For example, 
07
08Given the tree:
09        4
10       / \
11      2   7
12     / \
13    1   3
14And the value to insert: 5
15You can return this binary search tree:
16
17         4
18       /   \
19      2     7
20     / \   /
21    1   3 5
22This tree is also valid:
23
24         5
25       /   \
26      2     7
27     / \   
28    1   3
29         \
30          4
31**/
32
33//Your runtime beats 97.67 % of cpp submissions.
34
35/**
36 * Definition for a binary tree node.
37 * struct TreeNode {
38 *     int val;
39 *     TreeNode *left;
40 *     TreeNode *right;
41 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
42 * };
43 */
44class Solution {
45public:
46    TreeNode* insertIntoBST(TreeNode* root, int val) {
47        if(root==NULL){
48            return new TreeNode(val);
49        }else if(val < root->val){
50            root->left = insertIntoBST(root->left, val);
51        }else if(val > root->val){
52            root->right = insertIntoBST(root->right, val);
53        }
54        return root;
55    }
56};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.