Tree traversals: pre-order, in-order, post-order and level order
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A traversal visits every node of a tree exactly once. Walk a 7-key binary search tree and see that pre-order, in-order and post-order are one recursive walk that passes each node three times; only the pass that prints changes. Then switch to a queue for level order. The Software lesson "Trees" covers search, insert and a tree that turns into a line, and "Comparing growth rates: O, Omega and Theta" defines the Θ used for the cost.
One tree, four orders
This binary search tree holds 7 keys: smaller keys sit to the left, bigger to the right. A traversal visits every node exactly once. The question is in what order. Four standard orders give four different lists from the same tree.
40
/ \
20 60
/ \ / \
10 30 50 70
n = 7 nodes, height 2
left subtree < node < right subtree
from collections import deque
class Node:
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right = key, left, right
root = Node(40, Node(20, Node(10), Node(30)),
Node(60, Node(50), Node(70)))اقرأ الدرس خطوة بخطوة
One tree, four orders
This binary search tree holds 7 keys: smaller keys sit to the left, bigger to the right. A traversal visits every node exactly once. The question is in what order. Four standard orders give four different lists from the same tree.
40 / \ 20 60 / \ / \ 10 30 50 70 n = 7 nodes, height 2 left subtree < node < right subtree from collections import deque class Node: def __init__(self, key, left=None, right=None): self.key, self.left, self.right = key, left, right root = Node(40, Node(20, Node(10), Node(30)), Node(60, Node(50), Node(70)))One walk, three passes
Recursion walks the tree the same way every time: go left, come back, go right, come back. Follow the dot round the outside. It passes each node three times: on the way down, between its children, and on the way back up.
the walk round the tree pass 1 arriving, before the left child pass 2 between left and right child pass 3 leaving, after the right child 7 nodes × 3 passes = 21 passesThe code: three slots
In Python the walk is a function that calls itself on the left child, then on the right. The print can sit in one of three slots: before both calls, between them, or after both. Each slot matches one pass.
1 def dfs(n, slot): 2 if n is None: return 3 if slot == 1: print(n.key) 4 dfs(n.left, slot) 5 if slot == 2: print(n.key) 6 dfs(n.right, slot) 7 if slot == 3: print(n.key) slot 1 (line 3): pre-order slot 2 (line 5): in-order slot 3 (line 7): post-orderPre-order: node first
Pre-order prints a node on the first pass, before its children, so the root comes first: 40 20 10 30 60 50 70. Every parent is printed before its children, which is the order you need to copy a tree.
dfs(root, 1) node, then left subtree, then right subtree printed: 40 20 10 30 60 50 70 parents before childrenIn-order: sorted keys
In-order prints on the second pass: after the whole left subtree, before the right one. In a binary search tree everything left is smaller, so the keys come out sorted: 10 20 30 40 50 60 70.
dfs(root, 2) left subtree, then node, then right subtree printed: 10 20 30 40 50 60 70 a BST in-order is always sortedPost-order: children first
Post-order waits for the third pass, when both children are done: 10 30 20 50 70 60 40. The root comes last. Use it when a node needs its children finished first, like deleting a tree or adding up folder sizes.
dfs(root, 3) left subtree, then right subtree, then node printed: 10 30 20 50 70 60 40 children before parentsAll three cost Θ(n)
All three orders are the same walk, so they cost the same. dfs runs once per node, plus once per empty child, which returns at once. 7 nodes have 8 empty children: 15 calls, 2n + 1. That is Θ(n) time.
calls on a node 7 calls on an empty child 8 total 15 any binary tree with n nodes has n + 1 empty children, so dfs runs 2n + 1 times: Θ(n)Level order needs a queue
Level order reads the tree row by row, top to bottom, left to right. The walk cannot do that: it dives down first. A queue can. It is a line: add at the back, take from the front. Start with the root in it.
1 def bfs(root): 2 q = deque([root]) 3 while q: 4 n = q.popleft() 5 print(n.key) 6 for c in (n.left, n.right): 7 if c: q.append(c) queue: [40] deque: O(1) append and popleftLevel order: row by row
Repeat: take the front node, print it, add its children at the back. Children wait behind everything already in line, so each row prints before the next: 40 20 60 10 30 50 70.
take 40, printqueue [] add 20 queue [20] add 60 queue [20, 60] take 20, printqueue [60] add 10 queue [60, 10] add 30 queue [60, 10, 30] take 60, printqueue [10, 30] add 50 queue [10, 30, 50] add 70 queue [10, 30, 50, 70] take 10, printqueue [30, 50, 70] take 30, printqueue [50, 70] take 50, printqueue [70] take 70, printqueue [] printed: 40 20 60 10 30 50 70
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01In the lesson's tree (40 at the root; 20 and 60 below it; then 10, 30, 50, 70), what does post-order print?
Post-order prints a node on its third pass, after both subtrees: 10 and 30 before 20, 50 and 70 before 60, and the root 40 last. The other options are pre-order, in-order and level order.
02Why does in-order on a binary search tree print the keys in sorted order?
In a BST every key on the left is smaller and every key on the right is bigger. In-order prints left subtree, node, right subtree, and the same holds inside each subtree, so the keys come out in increasing order.
03You want to delete every node of a tree, and a node can only be freed once its children are gone. Which order fits?
Post-order handles both children before the node itself, so every child is already deleted when its parent is reached.
04Level order on the lesson's tree has printed 40 and 20. What is in the queue, front first?
Taking 40 adds 20 and 60. Taking 20 prints it and adds 10 and 30 at the back, behind 60. So the queue is [60, 10, 30], and 60 prints next: the rest of row 1 before row 2.
05dfs(n, slot) is called on every node and on every empty child. How many calls does it make on a binary tree with 100 nodes?
A binary tree with n nodes has n + 1 empty child links, so there are n + (n + 1) = 2n + 1 calls: 201. Each does constant work, so the traversal is Θ(n).
المسرد
- Traversal
- A way of visiting every node of a tree exactly once, in a fixed order.
- Pre-order
- Visit the node, then its left subtree, then its right subtree. Parents come before their children.
- In-order
- Visit the left subtree, then the node, then the right subtree. On a binary search tree this gives the keys in sorted order.
- Post-order
- Visit the left subtree, then the right subtree, then the node. Children come before their parents.
- Level order
- Visit the nodes row by row from the root down, left to right in each row. Also called breadth-first order.
- Depth-first
- Going as deep as possible down one branch before backing up. Pre-, in- and post-order are all depth-first.
- Queue
- A first-in, first-out line: add at the back, take from the front. In Python, collections.deque with append and popleft.
- Subtree
- A node together with everything below it.
الملاحظات والمصادر
- The three passes are the times the recursion is at a node: when dfs(n) starts, when dfs(n.left) returns, and when dfs(n.right) returns. A real program prints in only one of the slots; the figure shows all three so you can compare them.
- Each call does O(1) work besides its two recursive calls, and a binary tree with n nodes has n + 1 empty child links, so dfs is called 2n + 1 times (15 here). CLRS Theorem 12.1 proves the same Θ(n) bound for the in-order walk.
- The recursion keeps one call frame per level it is inside: at most the height plus 2 frames (here 4). For a tree that has turned into a line that is n + 1 frames, and Python stops at about 1000 by default (sys.getrecursionlimit()). The queue in level order holds at most about one row: in a full tree, up to (n + 1)/2 nodes (here 4).
- The code is real Python 3. With the Node class and root from the details panel, dfs(root, 2) prints 10 20 30 40 50 60 70 one per line, and bfs(root) prints 40 20 60 10 30 50 70. collections.deque is used because list.pop(0) moves every other item.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 6: Binary Trees, Part 1
- Sedgewick and Wayne, Algorithms 4th ed., §3.2 Binary Search Trees
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §12.1
- Tree traversal (pre-order, in-order, post-order, breadth-first)
- Python documentation: collections.deque
- Python tutorial: Using lists as queues
اختبار يتاح بعد الخطوة الأخيرة.