#701

Insert into a Binary Search Tree

pupil · 510 · lc medium +27 · verified · 73.4% accepted · 6,416 likes · top 84%

Description

Given the root of a binary search tree (BST) and a value that is guaranteed not to already exist in the tree, insert value while maintaining the BST property. Return the root of the resulting tree. Multiple valid insertion points may exist; any valid result is acceptable.

Example 1:

Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]
Explanation: Another accepted tree is:

Example 2:

Input: root = [40,20,60,10,30,50,70], val = 25
Output: [40,20,60,10,30,50,70,null,null,25]

Example 3:

Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
Output: [4,2,7,1,3,5]

Code

1
2
3
4
5
6
7
8
9