Skip to contentKEEP THE CRAFTTHE SANCTUARY

Build and Query a Binary Search Tree

Insert values into a binary search tree, read them back with an in-order traversal, and answer search queries by walking down one path.

The problem

Implement bst_operations(values, queries). Insert the values one by one, in the given order, into an empty binary search tree: a smaller value goes into the left subtree, a larger value into the right subtree, and a value that is already in the tree is ignored. Then return [in_order, found]: - in_order lists the tree's values with an in-order traversal (left subtree, node, right subtree), which visits them in increasing order. - found has one True or False per query: whether that query is in the tree. A TreeNode class with val, left and right is already defined for you, as on LeetCode: TreeNode(5) makes a node with no children. Search by walking down the tree, not by scanning a list. Example: values [5, 3, 7, 2, 4] and queries [4, 6] give [[2, 3, 4, 5, 7], [True, False]].

Starter code

def bst_operations(values, queries):
    pass

Public examples

  1. values = [5, 3, 7, 2, 4], queries = [4, 6]gives[[2, 3, 4, 5, 7], [True, False]]
  2. values = [2, 1, 2, 3, 1], queries = [1, 2, 4]gives[[1, 2, 3], [True, True, False]]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.