Insert a value into a binary search tree
A binary search tree keeps, for every node, all smaller values in its left subtree and all larger values in its right subtree. Given the root of such a tree and a value that is not in it yet, insert the value as a new leaf and return the root.
Walk down from the root: go left when the value is smaller than the node, right when it is larger, and attach the new node where the walk finds no child. Do not rebalance the tree (that means reorganising it to keep it short) or restructure it in any other way. If the tree is empty, the new node is the root.
Trees are written in level order, with null for a missing child.
Examples
Constraints
- The tree has between 0 and 100,000 nodes with distinct values
- All values, including value, are 32-bit integers
- value is not in the tree
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.