Inorder is sorted
After this: Use the inorder walk to list keys in order and to find the keys in a range.
On this page · 8 sections · 4 checks
So far we have used a BST to find one key at a time. A BST can also do something that a hash map cannot: it can give you all its keys in sorted order, and nothing has to be sorted to do it.
The tool is the inorder walk from the binary trees tutorial. At each node, the walk does three things in this order: go through the left subtree, visit the node, go through the right subtree.
The smallest example
Take the tree of three keys.
- Go through the left subtree. It is the single key 30, so write down 30.
- Visit the node. Write down 50.
- Go through the right subtree. It is the single key 70, so write down 70.
The result is 30, 50, 70, which is sorted.
The example tree
Now do the same on the example tree. The walk treats each subtree in the same way.
- Left subtree of 50. This is 30 with its children, so the same three steps give 20, 30, 40.
- Visit 50.
- Right subtree of 50. This is 70 with its children, so the same three steps give 60, 70, 80.
The keys come out as 20, 30, 40, 50, 60, 70, 80. Nobody sorted anything.
Why it is sorted
The walk visits a node after its whole left subtree and before its whole right subtree. In a BST, every key in the left subtree is smaller than the node, and every key in the right subtree is larger. So at the root, the output is every key below 50, then 50, then every key above 50. The same reasoning holds inside each subtree, so the whole list is in order.
The shape of the tree plays no part. The chain from Why the shape matters also comes out as 10, 20, 30, 40.
What this gives you
A hash map finds a key quickly, but it knows nothing about which key comes next. A BST keeps its keys in order, so it can answer questions about order. Here n is the number of keys and h is the height.
- List all keys in sorted order. This visits every node, so it is O(n): the work grows with the number of keys.
- Find the smallest or the largest key, by going as far left or as far right as possible. This is O(h).
- Find the smallest key above some value. This follows one path, so it is also O(h).
- Find all keys between two values. This is called a , and the walk only has to visit the parts of the tree that can hold those keys.
The code
def inorder(self): keys = [] self._inorder(self.root, keys) return keys
def _inorder(self, node, keys): if node is None: return self._inorder(node.left, keys) # everything smaller... keys.append(node.key) # ...then this key... self._inorder(node.right, keys) # ...then everything larger
def between(self, lo, hi): """Keys with lo <= key <= hi, in order, skipping subtrees that cannot hold any.""" keys = [] self._between(self.root, lo, hi, keys) return keys
def _between(self, node, lo, hi, keys): if node is None: return if lo < node.key: # only then can the left side hold a key >= lo self._between(node.left, lo, hi, keys) if lo <= node.key <= hi: keys.append(node.key) if node.key < hi: # only then can the right side hold a key <= hi self._between(node.right, lo, hi, keys) List<Integer> inorder() { List<Integer> keys = new ArrayList<>(); inorder(root, keys); return keys; }
private void inorder(Node node, List<Integer> keys) { if (node == null) return; inorder(node.left, keys); // everything smaller... keys.add(node.key); // ...then this key... inorder(node.right, keys); // ...then everything larger }
/** Keys with lo <= key <= hi, in order, skipping subtrees that cannot hold any. */ List<Integer> between(int lo, int hi) { List<Integer> keys = new ArrayList<>(); between(root, lo, hi, keys); return keys; }
private void between(Node node, int lo, int hi, List<Integer> keys) { if (node == null) return; if (lo < node.key) between(node.left, lo, hi, keys); // only then can the left side hold a key >= lo if (lo <= node.key && node.key <= hi) keys.add(node.key); if (node.key < hi) between(node.right, lo, hi, keys); // only then can the right side hold a key <= hi }Here is how to read it.
inordercreates an empty list, passes it down, and returns it when the walk is finished.- The highlighted lines are the walk itself: the left subtree, then this key, then the right subtree.
betweenanswers a range query. It finds the keys fromlotohi, including both. It is the same walk with two tests added.- It goes left only if the node's key is above
lo. If the key isloor lower, every key on the left is too small. - It goes right only if the node's key is below
hi. If the key ishior higher, every key on the right is too large.
Let us trace between(35, 65) on the example tree.
- At 50, the key is above 35, so go left.
- At 30, the key is not above 35, so skip its left subtree. 20 is never visited. 30 is outside the range, so it is not kept. 30 is below 65, so go right.
- 40 has no children, and it is inside the range. Keep 40.
- Back at 50, the key is inside the range. Keep 50. It is below 65, so go right.
- At 70, the key is above 35, so go left.
- 60 has no children, and it is inside the range. Keep 60.
- Back at 70, the key is outside the range. It is not below 65, so skip its right subtree. 80 is never visited.
The answer is 40, 50, 60, and the walk never touched 20 or 80.
The next block prints the full sorted list, then this range.
t = BST()for k in [50, 30, 70, 20, 40, 60, 80]: t.insert(k)print(t.inorder())print(t.between(35, 65))[20, 30, 40, 50, 60, 70, 80] [40, 50, 60]
BST t = new BST();for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) t.insert(k);System.out.println(t.inorder());System.out.println(t.between(35, 65));[20, 30, 40, 50, 60, 70, 80] [40, 50, 60]
Watch it happen
Run inorder, insert 45, and run inorder again. 45 lands between 40 and 50 in the output, and nothing sorts it there.
- Inorder traversalRun inorder. Watch the visited strip fill in sorted order: 20, 30, 40, 50, 60, 70, 80.
- Insert 45
- Inorder traversal
Run an operation to begin.
Check yourself
Why does an inorder walk of a binary search tree produce the keys in sorted order?
What does this print?
t = BST()for k in [50, 30, 70, 20, 40, 60, 80]: t.insert(k)print(t.inorder())print(t.between(35, 65))BST t = new BST();for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) t.insert(k);System.out.println(t.inorder());System.out.println(t.between(35, 65));Complete the inorder walk: between the two recursive calls, add this node's key to the list.
def inorder(node, keys): if node is None: return inorder(node.left, keys) ______________________ # ← visit: record this node's key inorder(node.right, keys)static void inorder(Node node, List<Integer> keys) { if (node == null) return; inorder(node.left, keys); ______________________ // ← visit: record this node's key inorder(node.right, keys);}This code builds the example tree, then does an insert and a delete. What does the last line print?
t = BST()for k in [50, 30, 70, 20, 40, 60, 80]: t.insert(k)t.insert(45)t.delete(30)print(t.inorder())BST t = new BST();for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) t.insert(k);t.insert(45);t.delete(30);System.out.println(t.inorder());Connect
- Explain why the inorder walk of a BST is sorted, from the rule and the order of the visits.
- Use the walk to list the keys in order, and skip subtrees to answer a range query.
- Name the questions about order that a BST can answer and a hash map cannot.