Picture a tree, walk it in the four orders, search, insert and delete in a binary search tree, see why a sorted insertion order makes it a chain, and build your own.
You are building the folder view of a cloud drive. A folder holds files and other folders. Each of those folders holds more of both. Open one folder, and you find the next level down.
A list cannot hold that shape. Items in a list sit one after another. A folder sits inside another folder, and the folders form levels. That shape is a tree.
Think of the folders on a laptop. One top folder holds two folders. Each of those holds two more. Every folder except the top one sits inside exactly one other folder.
Here is how the picture maps to a tree. Each folder is a node, and the top folder is the root. "Sits inside" is the link from a parent to its child. To reach a folder, you start at the top and open one folder at a time: the links are the only way to move around.
Folders on a laptop: one top folder holds folders, and each of those holds more. Every folder sits inside exactly one other. This shape is a tree.
A tree is a set of nodes joined by links, where every node except one has exactly one link coming from above. Seven words appear in every tree problem:
Some books and interview sites count height in links instead, so a single node has height 0 there. Both are correct. This course counts levels, so height = deepest depth + 1. Always say which one you mean.
A binary tree limits every node to at most two children, called the left child and the right child. In memory, a node is a value and two pointers, left and right. A pointer with nothing to point at is null.
Step by step: A tree in memory. The animated player loads in your browser.
Predict what happens
Q A tree has a root, two children of the root, and one child under the left child. How many levels is that, and how many leaves does it have?
Answer: B
Count the root's level, the children's level and the level below the left child: 3 levels. A leaf has no children. The right child of the root has none, and the node under the left child has none. The left child has a child, so it is not a leaf.
Almost everything you do with a tree starts at the root and follows links down. We count the work in steps. A step is a node looked at or a link changed.
A traversal visits every node once. A tree has no "next node" the way a list has, so the order is a choice. Three orders use recursion: visit the node, the left subtree and the right subtree, in different orders.
All four visit every node once, so each costs n steps for n nodes.
Here is one tree, used in every example below, with all four orders written out. Trace each one with your finger before you look at the answer.
40
/ \
25 60
/ \ / \
10 30 50 70| Walk | Order of visits |
|---|---|
| Pre-order | 40, 25, 10, 30, 60, 50, 70 |
| In-order | 10, 25, 30, 40, 50, 60, 70 |
| Post-order | 10, 30, 25, 50, 70, 60, 40 |
| Level order | 40, 25, 60, 10, 30, 50, 70 |
An in-order walk visits the left subtree, then the node, then the right subtree. On a search tree it reads the values from smallest to largest.
Step by step: A pre-order walk. The animated player loads in your browser.
Step by step: An in-order walk. The animated player loads in your browser.
Step by step: A post-order walk. The animated player loads in your browser.
Step by step: A level-order walk. The animated player loads in your browser.
Exercise · Predict the output: What does the post-order walk print?. Seven ids are inserted, in this order, into an empty search tree. Then a post-order walk prints every id. What does it print?
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(node, value):
if node is None:
return Node(value)
if value < node.value:
node.left = insert(node.left, value)
else:
node.right = insert(node.right, value)
return node
def post_order(node, out):
if node is None:
return
post_order(node.left, out)
post_order(node.right, out)
out.append(node.value)
root = None
for v in [30, 10, 40, 20, 5, 35, 50]:
root = insert(root, v)
out = []
post_order(root, out)
print(*out)Predict what happens
Q A tree has the root 40, with left child 25 and right child 60. What does a post-order walk print?
Answer: C
Post-order visits the left subtree (25), then the right subtree (60), then the node itself (40). Pre-order would print 40, 25, 60, and in-order 25, 40, 60.
A tree of plain values has no order to use. A binary search tree adds one rule. For every node, the values in its left subtree are all smaller. The values in its right subtree are all larger.
That rule is a promise at every node. At the root 40, everything on the left is below 40 and everything on the right is above 40. The same holds again at 25, and again at 60.
Two things follow. A search can ignore a whole subtree at each step. And an in-order walk visits the values from smallest to largest.
To look for a value, start at the root. If it matches, you have found it. If the value is smaller, go left, and if it is larger, go right. A missing child (null) means the value is not in the tree.
Trace two searches in the tree above:
Each step throws away a whole subtree. The cost is the number of nodes on the path, so it depends on the height of the tree, not on the nodes in the branches you skip.
Searching a binary search tree: at each node, go left for a smaller value and right for a larger one. Every step throws away a whole subtree.
Step by step: Search for 50. The animated player loads in your browser.
Step by step: Search for 55, which is not there. The animated player loads in your browser.
Exercise · Put it in order: Search a tree kept in lists. A search tree is stored as three lists. Node 0 is the root, node i holds values[i], and left[i] and right[i] are the nodes below it, or -1 for none. Arrange the lines into a search that returns whether the target is in the tree.
def contains(values, left, right, target):
node = 0 if values else -1
while node != -1:
if values[node] == target:
return True
if target < values[node]:
node = left[node]
else:
node = right[node]
return False
while node != 0:Insert follows the same path as a search for the new value. It ends at a missing child, and the new node goes there. Nothing else moves: one node is made and one link is changed.
Insert follows the same path as a search for the new value. It ends at a missing child, where the new node is linked in. Nothing else moves.
Step by step: Insert 45 into a search tree. The animated player loads in your browser.
Predict what happens
Q A search tree has the root 40, with left child 25 and right child 60. You insert 45. Where does the new node go?
Answer: C
45 is larger than 40, so go right to 60. 45 is smaller than 60, so go left. That child is missing, so the new node becomes the left child of 60. The root never changes.
Delete first finds the node. Then there are three cases.
A leaf. Cut the link from its parent. One link changes.
One child. Link the node's parent to its only child, so the child takes its place.
Two children. One parent link cannot hold two children. Find the in-order successor: the smallest value in the right subtree (go right once, then left as far as you can). Copy its value into the node you are deleting.
Then delete the successor from the right subtree. The successor has no left child, so that second delete is case 1 or case 2.
The in-order successor is the next value up in sorted order, so putting it in the gap keeps every left value smaller and every right value larger.
Trace it in the tree above. Delete 25, which has two children. Go right once to 30, then left as far as you can: 30 has no left child, so 30 is the successor.
Copy 30 into 25's place, then remove the old 30, which is a leaf. The left side of 40 is now 30, with 10 on its left. The in-order walk is 10, 30, 40, 50, 60, 70: still sorted.
Step by step: Delete 25, which has two children. The animated player loads in your browser.
Step by step: Delete 70, a leaf. The animated player loads in your browser.
Exercise · Find the bug: The successor from the wrong side. This function should return the in-order successor of a node that has two children: the value that takes its place when the node is deleted. It returns the wrong value. Which line is wrong?
def successor(node):
cur = node.left
while cur.left:
cur = cur.left
return cur.valueSearch, insert and delete each follow one path from the root down, so they cost the height. Everything now depends on the shape.
A balanced tree is wide and short. The usual exact rule: at every node, the heights of the left and right subtrees differ by at most 1. Then each level holds about twice as many nodes as the one above. A balanced tree of a million values is about 20 levels tall, and a search looks at about 20 nodes.
A skewed tree is a chain. Insert 10, 20, 30, 40 and 50 in sorted order: each new value is larger than all before it, so it always goes right. The tree has n levels, and a search looks at every node, as in a linked list.
The shape depends on the order of insertion. Random order usually gives a fairly balanced tree. Sorted order, which real data often arrives in, gives a chain.
Self-balancing trees repair their own shape as they grow. You do not build one here, but you should know they exist.
Values inserted in sorted order always go right, so the tree becomes a chain. A search then looks at every node, like a linked list.
Step by step: Search a balanced tree of six values. The animated player loads in your browser.
Step by step: Search a tree built from sorted values. The animated player loads in your browser.
Predict what happens
Q You insert 10, 20, 30, 40, 50 and 60, in that order, into an empty search tree. How many nodes does a search for 60 look at?
Answer: C
Each value is larger than every value before it, so it goes to the right of the last one. The tree is a chain of 6 nodes, and 60 is at the bottom. Search can only halve a tree that is balanced.
Here is every operation side by side, with a sorted array as a comparison. The last row is the one that decides everything.
| Operation | Balanced search tree | Skewed search tree (a chain) | Sorted array | What sets the cost |
|---|---|---|---|---|
| Search for a value | O(log n): one path of about log n nodes | O(n): every node is on the path | O(log n) with binary search | The height of the tree |
| Insert a value | O(log n): find the spot, change one link | O(n) | O(n): later values shift along | Walking down to the spot |
| Delete a value | O(log n): find it, relink | O(n) | O(n): later values shift back | Finding it, then at most a second walk for the successor |
| Smallest or largest value | O(log n): keep going left, or right | O(n) | O(1): the first or last cell | The height again |
| Walk every node (any traversal) | O(n) | O(n) | O(n) | Every node is visited once |
| Height of the tree | About log n levels | n levels | Not a tree | How balanced the insertion order was |
| Memory for each value | One node: the value and two pointers | The same | One cell | A tree pays for pointers |
A balanced search tree keeps a sorted collection that you can change cheaply. A sorted array searches as fast, but every insert and delete shifts values. A skewed tree gives up every advantage, so the insertion order matters.
Now drive the tree yourself. Type a value, then use the buttons for search, insert and delete, or start a walk. Each operation runs step by step. The step counter shows the cost, and the tree's height and size are shown under the picture.
Try these six, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the structure yourself. The lab gives you a SearchTree class with a root node. Each node has a value, a left link and a right link, and all three are ready for you. You write five methods: insert, contains, in_order, size and height.
Three things to take care over:
insert ignores a value that is already in the tree, and returns true only when it adds a node.in_order returns the values from smallest to largest. If your tree is a valid search tree, they come out sorted.height is the number of levels. An empty tree has height 0, and a tree with one node has height 1.Each test creates a new, empty tree, calls your methods in order and compares every value they return. When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a search tree when you need values kept in order while you add and remove them. It answers "is this here?", "what comes next after this value?" and "what is the smallest value above 50?" in about log n steps. A walk in order prints everything sorted.
Plain trees, without the search rule, hold things that are nested by nature. Examples are folders, a comment thread, an org chart and a menu of categories.
Choose a hash map when you only look up exact keys and never need order: it is O(1) on average. Choose an array when you read by position. Choose a heap when you only ever need the smallest item. A search tree is the right tool when you need both lookups and order.
node.left.value < node.value and node.right.value > node.value for every node looks like a full check, but it is not. A tree where 55 sits in the left subtree of 40, as the right child of 30, passes at each parent, and breaks the rule at the root. Pass down the allowed range, (low, high), and check each node against it.
The classic mistake: checking each node only against its parent. Every pair can pass while one value still breaks the rule higher up the tree.
Exercise · Break it: Find the tree this check accepts. This function checks a search tree by comparing each node with its own children only. Find a tree that is not a valid search tree but that it accepts. The tree is a list in level order, left to right, row by row, where -1 means "no node" (every real id is positive).
def is_valid(node):
if node is None:
return True
if node.left and node.left.value >= node.value:
return False
if node.right and node.right.value <= node.value:
return False
return is_valid(node.left) and is_valid(node.right)A function that starts with node.value crashes on an empty tree, and on every missing child at the bottom. Begin each recursive function with if node is None: and decide what an empty tree returns: 0 for a height, an empty list for a walk, true for a "valid" check.
for id in sorted_ids: tree.insert(id) builds a chain, and every search then costs n steps. Shuffle the values before you insert them, or use a self-balancing tree from a library.
parent.left = None removes the whole subtree below the node, not only the node. A node with two children must take the value of its in-order successor, and then the successor is deleted from the right subtree.
Depth counts down from the root to a node. Height counts the levels of a whole tree. The deepest leaf has the biggest depth, and height = deepest_depth + 1. Say which one you mean, and whether the root is level 0 or level 1.
Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The picture
Q1/2 A tree has a root with three children. One of those children has two children of its own. How many leaves does the tree have?
Answer: B
A leaf has no children. The two grandchildren are leaves. Two of the root's three children have no children, so they are leaves too. The third child has children, so it is not a leaf.
Q2/2 A binary tree has one node at the top, two below it and one below each of those two. How many levels is its height, counting the root's level?
Answer: B
The top node is level 1, its two children are level 2 and their children are level 3. The height counts levels, so it is 3.
Checkpoint · The four walks
Q1/2 A tree has the root 40, with the left child 25 and the right child 60. Which walk prints 25, 40, 60?
Answer: B
In-order visits the left subtree, then the node, then the right subtree: 25, 40, 60. Pre-order gives 40, 25, 60, post-order gives 25, 60, 40, and level order gives 40, 25, 60.
Q2/2 You need to add up the size of a folder from the sizes of everything inside it. Which walk fits, and why?
Answer: C
Post-order visits a node after everything below it, so each child's total is ready when the parent is reached.
Checkpoint · The search tree
Q1/4 You search for 55 in a search tree. The root is 40. Which way do you go, and what do you throw away?
Answer: B
55 is larger than 40, so it can only be in the right subtree. Every value on the left is smaller than 40, so none of them can be 55.
Q2/4 Which walk of a binary search tree gives its values from smallest to largest?
Answer: B
In-order visits the smaller left subtree first, then the node, then the larger right subtree, at every node. That reads the values in sorted order.
Q3/4 A search tree has 15 values in a perfectly balanced tree of 4 levels. About how many nodes does a search look at, at most?
Answer: C
A search follows one path from the root to a leaf. The path has one node in each level, so it looks at 4 nodes, however many values the other branches hold.
Q4/4 You delete a node that has two children from a search tree. What takes its place?
Answer: C
The successor is the next value up in sorted order. Put it in the gap, and every left value stays smaller and every right value stays larger.
Checkpoint · Shape and mistakes
Q1/2 You insert 5, 4, 3, 2, 1 in that order into an empty search tree. What does it look like, and what does a search for 1 cost?
Answer: C
Each new value is smaller than all before it, so it goes to the left of the last one. The tree is a chain of 5 nodes, and 1 is at the bottom, so the search looks at all 5.
Q2/2 A tree passes this check at every node: the left child is smaller than the node, and the right child is larger. Is it always a valid search tree?
Answer: B
The rule covers whole subtrees, not only children. A 55 under the left side of 40 passes at its parent but breaks the rule at 40. Pass down the allowed range to catch it.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.