(Slides) 6 - Trees and Traversals
(Slides) 6 - Trees and Traversals
99
Xingcan
ITEC2620 O
Apr 2021
Tree Data Structure -- Example
Director
Manager Manager
100
Xingcan
ITEC2620 O
Apr 2021
Tree Data Structure -- Introduction
▪ Linear to Non-Linear
1
1 2 3 4 5 6 7
2 3 4 Hierarchical
5 6 7
101
Xingcan
ITEC2620 O
Apr 2021
Tree Data Structure -- Terminologies
1 Node Edge Internal Node Root (unique) Depth (the length to root) = 1
Level = Depth + 1 = 2
1
1 Ancestor of 3
2 3 4
2 Parent of 3
Sibling of 3 Degree (# of children) = 2 Height (the longest downward
5 6
4 3 Child of 2 path to a leaf node) = 1
subtree
103
Xingcan
ITEC2620 O
Apr 2021
Tree Data Structure – An Implementation
104
Xingcan
ITEC2620 O
Apr 2021
Tree Traversal
1 2 3 4 5 6 7
105
Xingcan
ITEC2620 O
Apr 2021
Tree Traversal
1 1
2 3 4 2 3 4
5 6 7 5 6 7
106
Xingcan
ITEC2620 O
Apr 2021
Depth-First Search – The Idea
▪ Starts at the root node and explores as far as possible along each branch
before backtracking.
1
▪ Backtracking:
▫ Search in branches and sub-branches
2 3 4
▫ Remember the visited branches
▫ Go to a previous location 5 6 7
▫ Search the next branch
Depth-First Search
107
Xingcan
ITEC2620 O
Apr 2021
Depth-First Search – The Implementation
▪ Recursion
2 3 4
5 6 7
Depth-First Search
108
Xingcan
ITEC2620 O
Apr 2021
Depth-First Search – The Implementation
▪ Stack
▫ Use a stack to “simulate” recursion
1
1 2 5 6
2 3 4
5
6 6 5 6 7
...
2 7 7 7
3 3 3 3 Depth-First Search
1 4 4 4 4
109
Xingcan
ITEC2620 O
Apr 2021
Breadth-First Search – The Idea
▪ Starts at the tree root and explores all of the sibling nodes at the present
depth prior to moving on to the nodes at the next depth level.
1
2 3 4
5 6 7
Breadth-First Search
(Level Order Search)
110
Xingcan
ITEC2620 O
Apr 2021
Breadth-First Search – The Implementation
7 6 5 4 3 1
2
2 3 4
5 6 7
Breadth-First Search
(Level Order Search)
111
Xingcan
ITEC2620 O
Apr 2021
The Maze Problem
A Block Path
112
Xingcan
ITEC2620 O
Apr 2021