* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
3.6 KiB
Executable File
Traversing a binary tree
In its physical representation, a tree is a linked data structure, so traversal follows pointers from node to node. Unlike a linked list, however, a tree is nonlinear. Traversing it is more complex and requires a search algorithm.
Common binary-tree traversals include level-order, preorder, inorder, and postorder traversal.
Level-order traversal
As shown below, level-order traversal visits the tree level by level from top to bottom, moving from left to right within each level.
Level-order traversal is a form of breadth-first traversal, also called breadth-first search (BFS). It explores outward one layer at a time.
Implementation
Breadth-first traversal usually uses a queue. A queue's first-in, first-out rule matches the traversal's level-by-level progression. The implementation follows:
[file]{binary_tree_bfs}-[class]{}-[func]{level_order}
Complexity analysis
- Time complexity: $O(n)$. Each of the
nnodes is visited once, takingO(n)time. - Space complexity: $O(n)$. In the worst case, a perfect binary tree, the queue holds up to
(n + 1) / 2nodes just before the lowest level is visited, requiringO(n)space.
Preorder, inorder, and postorder traversal
Preorder, inorder, and postorder traversal are forms of depth-first traversal, also called depth-first search (DFS). They follow a path to its end, then backtrack and continue.
The figure below illustrates depth-first traversal. Imagine walking once around the outside of the entire binary tree. At each node, you encounter three positions corresponding to preorder, inorder, and postorder visits.
Implementation
Depth-first search is usually implemented recursively:
[file]{binary_tree_dfs}-[class]{}-[func]{post_order}
!!! tip
Depth-first search can also be implemented iteratively. Interested readers can explore this approach themselves.
The figure below shows the recursive process for preorder traversal, with two opposing phases: descending into calls and returning from them.
- Descending starts a new function call and visits the next node.
- Returning ends a function call, indicating that the current node has been fully processed.
Complexity analysis
- Time complexity: $O(n)$. Every node is visited once, taking
O(n)time. - Space complexity: $O(n)$. In the worst case, the tree degenerates into a linked list, recursion reaches depth
n, and stack frames requireO(n)space.












