Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-025

BST Insert and Preorder Traversal

Problem

Insert values into an empty binary search tree in the given order, then insert key, and return the preorder traversal.

Duplicates are ignored, so each value appears at most once. Preorder visits a node first, then its left subtree, then its right subtree.

Return the list of node values in preorder.

Hint

Compare against each node and descend left when smaller, right when larger.

Test cases

case 1
in: [[5,3,8],4]
expected: [5,3,4,8]
case 2
in: [[],5]
expected: [5]
case 3
in: [[5,5],5]
expected: [5]
case 4
in: [[10,5,15,3],12]
expected: [10,5,3,15,12]
case 5
in: [[2,1,3],4]
expected: [2,1,3,4]
Starter codePython
def bst_insert(values, key):
    # Your code here
    pass

5 test cases · run your code against them in the editor