Skip to main content

Insert into a Binary Search Tree

Medium
Data Structures and Algorithms
Editorial
Topics:
Binary Search Tree
Binary Tree
Tree

A binary search tree (BST) is a binary tree in which every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. Each node may have zero, one, or two children. The root parameter is the root of the existing BST, represented in the input as a level-order array; null denotes a missing child.

Insert the integer in val while preserving the BST property. The value in val does not already occur in the tree. The usual result places val in a newly created leaf at the first available position along its search path, although any valid BST containing all original values and val is accepted.

Return the root of the resulting BST. If root is empty, create a single-node tree containing val. The returned tree is represented in level order, using null for missing children.

Example 1:

Input: root = [8,3,10,1,6,null,14], val = 7
Output: [8,3,10,1,6,null,14,null,null,null,7]
Explanation: Since 7 is less than 8 but greater than 3 and 6, it becomes the right child of 6.

Example 2:

Input: root = [], val = 12
Output: [12]
Explanation: An empty tree receives a new root node containing 12.

Example 3:

Input: root = [5,2,9,null,4,7,11], val = 1
Output: [5,2,9,1,4,7,11]
Explanation: The search moves left from 5 and then left from 2, so 1 is attached as the left child of 2.

Constraints:

  • 0 <= number of nodes in root <= 10^4
  • -10^8 <= value in each tree node <= 10^8
  • -10^8 <= val <= 10^8
  • root is either empty or represents a valid binary search tree
  • All values already present in root are distinct
  • val does not already exist in root

Need help or want more practice?

Practise in an interviewGet AI Coach help