Insert
Standard · Write code · about 10 min
Insert a new key val into the binary search tree with the given root and return the root of the resulting tree. The key is not yet in the tree. The new key becomes a leaf.
Example 1
Input:
[[4,2,7,1,3],5]
Output:
[4,2,7,1,3,5]
5 goes right of 4, then left of 7.
Example 2
Input:
[[],3]
Output:
[3]
Inserting into an empty tree makes the key the root.
Constraints
- 0 ≤ number of nodes ≤ 1,000
- Keys are distinct integers with -1,000 ≤ key ≤ 1,000
- The tree is a valid BST, given in level order; null marks a missing child
Learn the idea first: BST: search, insert, min and max, a visual lesson.
More BST: search, insert, min and max problems
- Insert a sequence Warm-up
- Search Standard
- Min and max Standard
- Closest value Challenge