Challenge 2
- Algorithms course
- Intermediate
- Lesson 78/80
- 4 min
Insert items into a BST and search.
Challenge 2: BST
In this challenge you will insert items into a BST and search. The tree is represented with lists.
Values: [5, 3, 7, 2, 4]. Search: 4. Output: True.
BST gives ordered search with left-smaller, right-larger rule; average O(log n).
Practice BST insert and search
Write bst_search(tree, val). Check if val exists in the tree. Print True with print(bst_search(build_bst([5, 3, 7, 2, 4]), 4)).
Starter code
def bst_search(tree, val):
# BST searchSample solution
def bst_search(tree, val):
# BST search
if tree is None:
return False
if tree[0] == val:
return True
if val < tree[0]:
return bst_search(tree[1], val)
return bst_search(tree[2], val)
def bst_insert(tree, val):
if tree is None:
return [val, None, None]
if val < tree[0]:
tree[1] = bst_insert(tree[1], val)
else:
tree[2] = bst_insert(tree[2], val)
return tree
def build_bst(values):
root = None
for v in values:
root = bst_insert(root, v)
return root
print(bst_search(build_bst([5, 3, 7, 2, 4]), 4))Expected output
True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Tree node
[val, ____, right]
[val, left, right]
Explanation: left is right.
2 Challenge 2: match the terms
| Term | Meaning |
|---|---|
BST |
Ordered tree |
left |
Smaller |
right |
Larger |
search |
Search |