Skip to the code
cf.
+10 XP

#336 Insert a Release Into the Version Tree

easy

A release dashboard keeps build numbers in a binary search tree so it can find the nearest build quickly. A new build number arrives and must be added.

Write addBuild(root, build) that inserts build as a new leaf in the only place the search tree rule allows (walk down from the root: left if smaller, right if bigger, until the spot is empty), and returns the root. build is never already in the tree. If the tree is empty, the new node is the root.

Example 1

Input: root = [8,3,10,1,6], build = 5
Output: [8,3,10,1,6,null,null,null,null,5]

5 < 8 go left, 5 > 3 go right, 5 < 6 and 6 has no left child: attach it there.

Example 2

Input: root = [], build = 7
Output: [7]

An empty tree gets a new root.

Constraints

  • 0 <= number of builds <= 10000
  • All build numbers are unique.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).