Trees and binary search treestree-inorder
Lesson·difficulty 3/5·~14 min
Trees: in-order traversal
Trees: in-order traversal
An in-order traversal visits a binary tree in the order: left subtree, then this node, then right subtree. The magic trick: do this on a binary search tree and the values come out sorted. (That's not a coincidence — it's the whole point of a BST.)
Walk build_bst([5, 3, 8, 2, 4, 7]) left → node → right and the values fall
out already sorted:
text
5
/ \
3 8
/ \ /
2 4 7 visit order: 2 → 3 → 4 → 5 → 7 → 8 (sorted!)
The trees here are built by build_bst(values), which inserts each int in
order, sending values < node left and >= right.
Your task
Write inorder(root) returning a list of the values in in-order
(left, node, right). For a BST that list is sorted ascending.
python
inorder(build_bst([5, 3, 8, 2, 4, 7])) # [2, 3, 4, 5, 7, 8]
inorder(build_bst([])) # []
inorder(build_bst([3, 1, 2])) # [1, 2, 3]
Hint: an empty node yields []; otherwise glue together
inorder(left) + [root.val] + inorder(right).
Tests
- six values
- empty tree
- single node
- unsorted in (hidden)
- with dupes (hidden)
Stuck? Ask for a spark
warming up
Loading editor…
$ Console output will appear here.