DSA L9
DSA L9
Tree Traversal
DR . MOHAMMED AL-HUBAISHI
Tree Traversal Understanding Different
Ways to Navigate Tree
Techniques Data Structures
3
Introduction
Implementation: D E
preorder(node):
Pre-order Output:
if node:
A→B→D→E→C
print(node.data)
preorder(node.left)
preorder(node.right)
In-order Traversal
- Expression evaluation
Explanation: Pre-order traversal is used to evaluate prefix
expressions (Polish notation). In this notation, operators appear
before their operands.
Example : Expression: + * 3 4 5 (Prefix notation)
- Pre-order traversal: `+ * 3 4 5`
- Evaluation: 3 * 4 = 12, then 12 + 5 = 17.
Applications of In-order Traversal
- Directory listings
Explanation: In-order traversal is used to list files and directories in a
hierarchical structure, such as a file system. It ensures that directories and files
are visited in a sorted or logical order.
Example: Directory Tree:
- In-order traversal: `File1 -> Folder1 -> Root -> Folder2 -> File2`
- Output: Files and folders are listed in a logical order.
Applications of Post-order Traversal
- Copy operations
Explanation: Post-order traversal is used to copy a tree structure. It
ensures that all child nodes are processed before the parent node,
which is essential for duplicating hierarchical data.
- Post-order traversal: `D -> E -> B -> C -> A`
- Copy Process: Start with the leaf nodes (`D` and `E`), then move
up to their parent (`B`), and so on, until the entire tree is copied.
16
C++ code
https://onlinegdb.com/zP0H_-IkM
17
test the code
https://onlinegdb.com/zP0H_-IkM
18
Illustrations for Traversals (Contd.)
Binary Search Trees: Traversals are crucial for searching, inserting, and
deleting nodes in binary search trees.
root
29
Book References
30