---
tags: leetcode
---
# [701. Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/)
---
# My Solution
## The Key Idea for Solving This Coding Question
## C++ Code
```cpp=
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode *insertIntoBST(TreeNode *root, int val) {
TreeNode *newNode = new TreeNode(val);
if (root == nullptr) {
return newNode;
}
TreeNode *node = root;
while (node != nullptr) {
if (node->val < val) {
if (node->right == nullptr) {
node->right = newNode;
break;
}
node = node->right;
} else {
if (node->left == nullptr) {
node->left = newNode;
break;
}
node = node->left;
}
}
return root;
}
};
```
## Time Complexity
$O(logn)$
n is the number of nodes in the BST.
## Space Complexity
$O(1)$
<!--
# Miscellane
# Test Cases
```
[4,2,7,1,3]
5
```
```
[40,20,60,10,30,50,70]
25
```
```
[4,2,7,1,3,null,null,null,null,null,null]
5
```
```
[]
5
```
```
[4,2,7,1,3]
8
```
```
[4,2,7,1,3]
5
```
```
[18,2,22,null,null,null,63,null,84,null,null]
10
```
-->