0% found this document useful (0 votes)
7 views

Lecture05 Tree

Uploaded by

Dheemant Rastogi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lecture05 Tree

Uploaded by

Dheemant Rastogi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 126

MH1403 Algorithms and Computing

Lecture 5 Tree

1
Outline

• Tree
• Binary tree
• Tree Traversal

2
Tree

3
Tree
• We have learned four data structures:
• Array, linked list, stack and queue
• These four data structures are linear data structure
(the data are arranged as a sequence)
• However, some data naturally comes with a
hierarchy. It is inconvenient to store and
process these data using linear data structure
• Example: files and folders in a computer system,
• Example: decision tree in machine learning
(classification trees, regression trees)

4
Tree

• Tree is a hierarchical data structure


• Tree is a collection of nodes
• The nodes are organized like an upside down tree
• Each node consists of some value, together with
some references to other nodes
• In this course, we will learn
• the general concepts and operations of tree
• the search tree (binary search tree, AVL tree)

5
Tree
• A tree data structure
stores information in
nodes root
• Similar to linked list
• There is a first node (the first
node is called root in tree)
• Each node, other than the
root, has exactly one node
pointing to it
• Different from linked list
• Each node in a tree may have
more than one references to
successors
• Each node in a linked list has
only one reference to a
successor
6
Tree
• We will learn the following concepts of tree:
• Root, internal, leaf nodes
• Parents, children, and siblings
• Paths, path length, height, and depth
• Ancestors and descendants
• Ordered and unordered trees
• Subtrees

7
Terminology: Parent

• A node is called the parent of a given node if this


node has reference pointing to that node
• Node H is the parent of Node I
• Node I is the parent of Node J, K, L
• For all nodes other than the root node, there is
one and only one parent node

8
Terminology: Child

• A node is called the child of a given node if the


given node has reference pointing to that node
• Example: Node I has three children: J, K and L
• All nodes have zero or more child nodes (children)

9
Terminology: Siblings

• Nodes with the same parent are siblings


• J, K, and L are siblings
• I and M are siblings

10
Terminology: degree

• The degree of a node is defined as the number


of its children
• Example: deg(I) = 3
deg(H) = 2

11
Terminology: leaf node, internal node

• Nodes with degree zero are called leaf nodes


• A leaf node does not point to any node
• Nodes which are not leaves are called internal
nodes

12
Leaf nodes:

13
Terminology: path

• A path is a sequence of nodes (a0, a1, ..., an),


where ak + 1 is a child of ak
• The length of this path is n
• Example, the path (B, E, G) has length 2

14
Example: Paths of length 10 (11 nodes) and 4 (5 nodes)

Start of these paths

End of these paths

15
Terminology: depth

• For each node in a tree, there exists a unique


path from the root node to that node
• The length (the number of edges) of this path is
the depth of the node
• Example: Node E has depth 2
Node L has depth 3

16
Terminology: level

• All the nodes with the same depth n are at the


same level n
• Example: Node C, E, I, M are at level 2
Node D, F, G, J, K, L are level 3

17
Nodes of depth up to 17
Level 0

Level 4

Level 9

Level 14

Level 17

18
Terminology: Height

• The height of a tree is defined as the maximum


depth of any node within the tree
• The height of a tree with one node is 0
• Note that a tree with one node contains only the root
node

19
The height of this tree is 17

17

20
Terminology: ancestor, descendent

• If a path exists from node a to node b:


• a is an ancestor of b
• b is a descendent of a

• Thus, a node is both an ancestor and a


descendant of itself
• We can add the adjective strict to exclude equality: a
is a strict descendent of b if a is a descendant of b
but a ≠ b

• The root node is an ancestor of all nodes

21
• The descendants of node B are B, C, D, E, F, and G:

• The ancestors of node I are I, H, and A:

22
All descendants (including itself) of the indicated node

23
All ancestors (including itself) of the indicated node

24
Terminology: subtree

• Given any node a within a tree T, the collection


of node a and all of its descendants is said to
be a subtree of the tree T

25
Binary Tree

26
Binary Tree

• In a binary tree, each node has at most two


children
• If a parent has two children, we can label the children
as left child and right child

27
Some binary tree examples with five nodes

28
Tree Traversal

29
Tree Traversal
• Tree traversal is a process to visit all the nodes of
a tree (and may print their values)
• A typical reason to traverse a tree is to display the data
stored at each node of the tree
• In this course, we learn four standard tree
traversal orderings:
• Preorder
• Inorder
• Postorder
• Level-order

30
Tree Traversal
• Depth-first traversal: go deeper in the tree before
exploring siblings
• Preorder
• Inorder
• Postorder
• Breath-first traversal: explore the breadth, i.e., full
width of the tree at a given level, before going
deeper
• Level-order
• We will learn the binary tree traversal in this course
• The traversals can be generalized to other trees
31
Traversals
A

B C

D E F G

H I

We’ll trace the different traversals using this tree; recursive calls,
returns, and “visits” will be numbered in the order they occur

32
Tree Traversal:
Depth-First Traversal

33
Preorder Traversal
• Start at the root
• Visit each node, followed by its left subtree, then right
subtree

• Recursive algorithm for preorder traversal:


• If tree is not empty,
• Visit root node of tree
• Perform preorder traversal of its left subtree
• Perform preorder traversal of its right subtree

34
Preorder Traversal
1: visit A
2 24
23 45
3: visit B 25: visit C
4 16 26 38
15 22 37 44 39:
5: visit D 17: visit E 27: visit F visit G

. . . .
6 18
. 7 14
8
19
20
9: visit H
21 28
34
35
29: visit I
36
40
41
42
43

10
. .11 12
13
30
. .31 32
33

Nodes are visited in the order ABDHECFIG


35
Preorder Traversal (to draw in lecture)

B C

D E F G

H I

36
Inorder Traversal
• Start at the root
• Visit the left subtree of each node, then the node,
then the right subtree of that node

• Recursive algorithm for inorder traversal:


• If tree is not empty,
• Perform inorder traversal of left subtree of root
• Visit root node of tree
• Perform inorder traversal of its right subtree

37
Inorder Traversal
23: visit A
1 24
22 45
14: visit B 37: visit C
2 15 25 38
13 21 36 44 41:
5: visit D 18: visit E 33: visit F
visit G

. . . .
3 16
. 4 12
6
17
19
9: visit H
20 26
32
34
29: visit I
35
39
40
42
43

7
. . 8 10
11
27
. .28 30
31

Nodes are visited in the order DHBEAIFCG


38
Inorder Traversal (to draw in lecture)

B C

D E F G

H I

39
Postorder Traversal
• Start at the root
• Visit the children of each node, then the node

• Recursive algorithm for postorder traversal


• If tree is not empty,
• Perform postorder traversal of left subtree of root
• Perform postorder traversal of right subtree of root
• Visit root node of tree

40
Postorder Traversal
45: visit A
1 23
22 44
21: visit B 43: visit C
2 14 24 36
13 20 35 42 41:
12: visit D 19: visit E 34: visit F
visit G

. . . .
3 15
. 4 11
5
16
17
10: visit H
18 25
31
32
30: visit I
33
37
38
39
40

6
. .7 8
9
26
. . 27 28
29

Nodes are visited in the order HDEBIFGCA


41
Postorder Traversal (to draw in lecture)

B C

D E F G

H I

42
Implementation of Depth-First Traversal
• Stack is needed for implementing depth-first traversal
• For example, for the tree shown below, for preorder traversal,
1) when we visit node A, before visiting its left child B, we need to
store its right child C so that we can visit C after visiting the
subtree rooted at B.
2) when visiting node B, before visiting its left child D, we need to
store its right child E
3) when visiting node D, before visiting its left child, we need to
store its right child H
4) we notice that we now stored nodes C, E, H, and we will visit
node H first, after visiting the subtree rooted at H, visit node E,
after visiting the subtree rooted at E, visit node C.
5) The node being stored most recently will be visited first (Last-
in-first-out), so stack is used

43
Implementation of Depth-First Traversal
• The simplest way to implement the depth-first
traversal is to use recursive functions
• Note that function calls are implemented using stack
(Before calling a function, the next code address is
stored on the stack. After the function call, pop the
code address from the stack and continue execution)
• An alternative way to implement the depth-first
traversal is to use the stack explicitly in the
iterative approach
• We will use preorder traversal as example to
illustrate the recursive and iterative approaches
in the following slides.
44
Example 1:
Recursive Implementation of Preorder Traversal

45
Recursive Preorder Traversal

• Recall that the preorder traversal is to:


• Start at the root
• Visit each node, followed by its left subtree, then right subtree
• The pseudo code of the recursive preorder traversal with
implicit stack is:

def preorder(root node):


if root node is not empty,
visit root node
preorder(root node’s left child)
preorder(root node’s right child)

• In the following slides, we show how this recursive function is


called to visit all the nodes in preorder
• These slides are created for you to get familiar with recursive function
46
• When writing code, we only need to call the function
preorder(), and pass node A as parameter to the function. Then
the function will call itself recursively.
preorder(A):
visit A
preorder(B)
preorder(C)

Visited nodes:
47
• Visit A

preorder(A):
visit A
preorder(B)
preorder(C)

Visited nodes: A
48
• Visit A’s left subtree rooted at B

preorder(A): preorder(B):
visit A visit B
preorder(B) preorder(D)
preorder(C) preorder(E)

Visited nodes: A
49
• Visit B

preorder(A): preorder(B):
visit A visit B
preorder(B) preorder(D)
preorder(C) preorder(E)

Visited nodes: A B
50
• Visit B’s left subtree rooted at D

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

Visited nodes: A B
51
• Visit D

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

Visited nodes: A B D
52
• Visit D’s left subtree (empty)

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

preorder(None):
do nothing

Visited nodes: A B D
53
• Visit D’ left subtree, do nothing, return

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

preorder(None):
do nothing

Visited nodes: A B D
54
• Visit D’s right subtree rooted at H

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

preorder(H):
visit H
preorder(None)
preorder(None)

Visited nodes: A B D
55
• Visit H

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

preorder(H):
visit H
preorder(None)
preorder(None)

Visited nodes: A B D H
56
• Visit H’s left subtree (empty)

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

preorder(None): preorder(H):
do nothing visit H
preorder(None)
preorder(None)

Visited nodes: A B D H
57
• Visit H’s left subtree, do nothing, return

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

preorder(None): preorder(H):
do nothing visit H
preorder(None)
preorder(None)

Visited nodes: A B D H
58
• Visit H’s right subtree (empty)

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

preorder(H):
visit H
preorder(None): preorder(None)
do nothing preorder(None)

Visited nodes: A B D H
59
• Visit H’s right subtree, do nothing, return

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

preorder(H):
visit H
preorder(None): preorder(None)
do nothing preorder(None)

Visited nodes: A B D H
60
• Finished visiting the subtree rooted at H, return

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

preorder(H):
visit H
preorder(None)
preorder(None)

Visited nodes: A B D H
61
• Finished visiting the subtree rooted at D, return

preorder(A): preorder(B): preorder(D):


visit A visit B visit D
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(H)

Visited nodes: A B D H
62
• After finish visiting B’s left subtree rooted at D, continue to
visit the B’s right subtree rooted at E
preorder(A): preorder(B): preorder(E):
visit A visit B visit E
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(None)

Visited nodes: A B D H
63
• Visit E

preorder(A): preorder(B): preorder(E):


visit A visit B visit E
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(None)

Visited nodes: A B D H E
64
• Visit E’s left subtree (empty). We omit this function call
here.
preorder(A): preorder(B): preorder(E):
visit A visit B visit E
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(None)

Visited nodes: A B D H E
65
• Visit E’s right subtree (empty). We omit here this function
call.
preorder(A): preorder(B): preorder(E):
visit A visit B visit E
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(None)

Visited nodes: A B D H E
66
• Finished visiting the subtree rooted at E, return

preorder(A): preorder(B): preorder(E):


visit A visit B visit E
preorder(B) preorder(D) preorder(None)
preorder(C) preorder(E) preorder(None)

Visited nodes: A B D H E
67
• Finished visiting the subtree rooted at B, return

preorder(A): preorder(B):
visit A visit B
preorder(B) preorder(D)
preorder(C) preorder(E)

Visited nodes: A B D H E
68
• Finished visiting A’s left subtree rooted at B, continue to visit
the A’s right subtree rooted at C
preorder(A): preorder(C):
visit A visit C
preorder(B) preorder(F)
preorder(C) preorder(G)

Visited nodes: A B D H E
69
• Visit C

preorder(A): preorder(C):
visit A visit C
preorder(B) preorder(F)
preorder(C) preorder(G)

Visited nodes: A B D H E C
70
• Visit the subtree rooted at F

preorder(A): preorder(C): preorder(F):


visit A visit C visit F
preorder(B) preorder(F) preorder(I)
preorder(C) preorder(G) preorder(None)

Visited nodes: A B D H E C
71
• Visit F

preorder(A): preorder(C): preorder(F):


visit A visit C visit F
preorder(B) preorder(F) preorder(I)
preorder(C) preorder(G) preorder(None)

Visited nodes: A B D H E C F
72
• Visit F’s left subtree rooted at I

preorder(A): preorder(C): preorder(F):


visit A visit C visit F
preorder(B) preorder(F) preorder(I)
preorder(C) preorder(G) preorder(None)

preorder(I):
visit I
preorder(None)
preorder(None)

Visited nodes: A B D H E C F
73
• Visit I

preorder(A): preorder(C): preorder(F):


visit A visit C visit F
preorder(B) preorder(F) preorder(I)
preorder(C) preorder(G) preorder(None)

preorder(I):
visit I
preorder(None)
preorder(None)

Visited nodes: A B D H E C F I
74
• Visit I’s left subtree (empty). We omit here this function call

preorder(A): preorder(C): preorder(F):


visit A visit C visit F
preorder(B) preorder(F) preorder(I)
preorder(C) preorder(G) preorder(None)

preorder(I):
visit I
preorder(None)
preorder(None)

Visited nodes: A B D H E C F I
75
• Visit I’s right subtree (empty). We omit here this function call

preorder(A): preorder(C): preorder(F):


visit A visit C visit F
preorder(B) preorder(F) preorder(I)
preorder(C) preorder(G) preorder(None)

preorder(I):
visit I
preorder(None)
preorder(None)

Visited nodes: A B D H E C F I
76
• Finished visiting the subtree rooted at I, return

preorder(A): preorder(C): preorder(F):


visit A visit C visit F
preorder(B) preorder(F) preorder(I)
preorder(C) preorder(G) preorder(None)

preorder(I):
visit I
preorder(None)
preorder(None)

Visited nodes: A B D H E C F I
77
• Finished visiting F’s left subtree rooted at I, continue to visit
F’s right subtree (empty). We omit this function call here.
preorder(A): preorder(C): preorder(F):
visit A visit C visit F
preorder(B) preorder(F) preorder(I)
preorder(C) preorder(G) preorder(None)

Visited nodes: A B D H E C F I
78
• Finished visiting the subtree rooted at F, return

preorder(A): preorder(C): preorder(F):


visit A visit C visit F
preorder(B) preorder(F) preorder(I)
preorder(C) preorder(G) preorder(None)

Visited nodes: A B D H E C F I
79
• Finished visiting C’ left subtree rooted at F, continue to visit
C’s right subtree rooted at G
preorder(A): preorder(C): preorder(G):
visit A visit C visit G
preorder(B) preorder(F) preorder(None)
preorder(C) preorder(G) preorder(None)

Visited nodes: A B D H E C F I
80
• Visit G

preorder(A): preorder(C): preorder(G):


visit A visit C visit G
preorder(B) preorder(F) preorder(None)
preorder(C) preorder(G) preorder(None)

Visited nodes: A B D H E C F I G
81
• Visit G’s left subtree (empty). We omit this function call
here.
preorder(A): preorder(C): preorder(G):
visit A visit C visit G
preorder(B) preorder(F) preorder(None)
preorder(C) preorder(G) preorder(None)

Visited nodes: A B D H E C F I G
82
• Visit G’s right subtree (empty). We omit this function call
here.
preorder(A): preorder(C): preorder(G):
visit A visit C visit G
preorder(B) preorder(F) preorder(None)
preorder(C) preorder(G) preorder(None)

Visited nodes: A B D H E C F I G
83
• Finished visiting the subtree rooted at G, return

preorder(A): preorder(C): preorder(G):


visit A visit C visit G
preorder(B) preorder(F) preorder(None)
preorder(C) preorder(G) preorder(None)

Visited nodes: A B D H E C F I G
84
• Finished visiting the subtree rooted at C, return

preorder(A): preorder(C):
visit A visit C
preorder(B) preorder(F)
preorder(C) preorder(G)

Visited nodes: A B D H E C F I G
85
• Finished visiting the tree rooted at A, return.
• Preorder traversal finishes.
preorder(A):
visit A
preorder(B)
preorder(C)

Return to the function/code that called preorder(A)

Visited nodes: A B D H E C F I G
86
Example 2:
Iterative Implementation of Preorder Traversal

87
Iterative Preorder Traversal

• To implement preorder traversal iteratively, we


use a stack explicitly
• The pseudo code is:
• Create a stack
• Push the root node onto the stack
• While the stack is not empty:
• Pop a node from the stack, visit this node
• Push this node’s right child onto the stack
• Push this node’s left child onto the stack
• The preorder traversal with this implementation is
illustrated in the following slides
88
Iterative Preorder Traversal

B C

D E F G

bottom stack top


H I

89
Iterative Preorder Traversal
• Start at the root. Push the root A onto the stack.

B C

D E F G

bottom stack top


H I
A

90
Iterative Preorder Traversal
• Pop the node A from the stack, visit node A.
• Push A’s right child C onto the stack,
• Push A’s left child B onto the stack
A

B C

D E F G

bottom stack top


H I
CB
Visited nodes: A
91
Iterative Preorder Traversal
• Pop the node B from the stack, visit node B.
• Push B’s right child E onto the stack
• Push B’s left child D onto the stack
A

B C

D E F G

bottom stack top


H I
CED
Visited nodes: A B
92
Iterative Preorder Traversal
• Pop the node D from the stack, visit node D.
• Push D’s right child H onto the stack
• No push operation
A

B C

D E F G

bottom stack top


H I
CEH
Visited nodes: A B D
93
Iterative Preorder Traversal
• Pop the node H from the stack, visit node H.
• No push operation
• No push operation
A

B C

D E F G

bottom stack top


H I
CE
Visited nodes: A B D H
94
Iterative Preorder Traversal
• Pop the node E from the stack, visit node E.
• No push operation
• No push operation
A

B C

D E F G

bottom stack top


H I
C
Visited nodes: A B D H E
95
Iterative Preorder Traversal
• Pop the node C from the stack, visit node C.
• Push C’s right child G onto the stack
• Push C’s left child F onto the stack
A

B C

D E F G

bottom stack top


H I
GF
Visited nodes: A B D H E C
96
Iterative Preorder Traversal
• Pop the node F from the stack, visit node F.
• No push operation
• Push F’s left child I onto the stack
A

B C

D E F G

bottom stack top


H I
G I
Visited nodes: A B D H E C F
97
Iterative Preorder Traversal
• Pop the node I from the stack, visit node I.
• No push operation
• No push operation
A

B C

D E F G

bottom stack top


H I
G
Visited nodes: A B D H E C F I
98
Iterative Preorder Traversal
• Pop the node G from the stack, visit node G.
• No push operation
• No push operation
A

B C

D E F G

bottom stack top


H I

Visited nodes: A B D H E C F I G
99
Iterative Preorder Traversal
• Stack is empty, finish.

B C

D E F G

bottom stack top


H I

Visited nodes: A B D H E C F I G
100
Tree Traversal:
Level-Order Traversal

101
Level Order Traversal

• Lever order traversal is also called breath first


traversal:
• Start at the root
• Visit the nodes at each level, from left to right

102
Level Order Traversal
A

B C

D E F G

H I

Nodes will be visited in the order ABCDEFGHI

103
Level Order Traversal
• Queue is needed for implementing level order
traversal
• For example, in the level order traversal shown below,
1) when we visit node B, before visiting node C, we need to
store node B’s children node D and E so that we can visit
these two nodes later.
2) when we visit node C, before visiting node D, we need to
store node C’s children node F and G.
3) we notice that we now stored nodes D, E, F, G, and we will
visit these nodes in the order of D, E, F and G. It is First-in-
first-out, so queue is needed

104
Level Order Traversal: Iterative

• To implement level order traversal, we will use a


queue
• The pseudo code using iterative approach is:
• Create a queue
• Enqueue the root node
• While the queue is not empty:
• Dequeue a node from the queue, visit this node
• Enqueue this node’s left child
• Enqueue this node’s right child
• The details of the above iterative level order
traversal is illustrated in the following slides
105
A

B C

D E F G

H I

106
Level Order Traversal

B C

D E F G

front queue rear


H I

107
Level Order Traversal
• Start at the root. Enqueue the root A

B C

D E F G

front queue rear


H I
A

108
Level Order Traversal
• Dequeue node A from queue, and visit node A
• Enqueue the children of A

B C

D E F G

front queue rear


H I
BC
Visited nodes: A 109
Level Order Traversal
• Dequeue node B from queue, and visit node B
• Enqueue the children of B

B C

D E F G

front queue rear


H I
CDE
Visited nodes: A B 110
Level Order Traversal
• Dequeue node C from queue, and visit node C)
• Enqueue the children of C

B C

D E F G

front queue rear


H I
DEFG
Visited nodes: A B C 111
Level Order Traversal
• Dequeue node D from queue, visit node D
• Enqueue the children of D

B C

D E F G

front queue rear


H I
EFGH
Visited nodes: A B C D 112
Level Order Traversal
• Dequeue node E from queue, and visit node E
• Enqueue the children of E ( no node)

B C

D E F G

front queue rear


H I
FGH
Visited nodes: A B C D E 113
Level Order Traversal
• Dequeue node F from queue, and visit node F
• Enqueue the children of F

B C

D E F G

front queue rear


H I
GHI
Visited nodes: A B C D E F 114
Level Order Traversal
• Dequeue G from queue, and visit node G
• Enqueue the children of G (no node)

B C

D E F G

front queue rear


H I
HI
Visited nodes: A B C D E F G 115
Level Order Traversal
• Dequeue node H from queue, and visit node H
• Enqueue the children of H (no node)

B C

D E F G

front queue rear


H I
I
Visited nodes: A B C D E F G H 116
Level Order Traversal
• Dequeue node I from queue, and visit node I
• Enqueue the children of I (no node)

B C

D E F G

front queue rear


H I

Visited nodes: A B C D E F G H I 117


Level Order Traversal
• The queue becomes empty, finish.

B C

D E F G

front queue rear


H I

Visited nodes: A B C D E F G H I 118


Level Order Traversal: Recursive
• In the previous slides, we illustrated the level order traversal using iterative
approach
• The recursive approach for the level order traversal is given below:
(the underscore prefix is a hint to the programmer that the variable,
method, or function is for internal use. The function _level_order()
will not be imported when you import the Python file containing this
function)
def _level_order(queue):
if queue is not empty:
dequeue a node from the queue
visit this node
enqueue this node’s left child
enqueue this node’s right child
_level_order(queue)

def level_order(root node):


create a queue
enqueue the root node
_level_order(queue)

• To apply the above code to the tree in the previous slide,


call level_order(node A)
119
Iteration vs. Recursion

120
Recursion vs. Iteration

• In the previous slides, the preorder traversal is


implemented using both the recursive and iterative
codes; the level order traversal is also implemented
using both the recursive and iterative codes.
• In general, when solving a problem involving
repeated computations, we can use either the
recursive or iterative approach. However, it may be
easier to describe some problems recursively; while
it may be easier to describe some problems
iteratively.
• We need to get familiar with recursion and iteration so that
we can choose a simpler approach to solve a problem
121
Recursion vs. Iteration

• Iterative code is in general a bit faster than


recursive function since implementing function call
requires extra operations
• If we need to repeat some computations too many
times (say, more than one million or one billion
times), we need to use iteration instead of recursive
function
• If there are too many iterations, the equivalent recursive
code would use up the stack allocated for implementing
the function calls of that program, then the program
crashes (you get the error message “too much
recursions”)
122
Conversion between recursion and iteration

• It is straightforward to convert iterative code (first


change the iterative code to while loop) to recursive
function
• But such conversion is normally not needed in applications
• In the example below, in the iterative code, the while loop is
used to repeat computation as long as the condition is true.
In the recursive code, repeating the computation is achieved
through calling itself, and stops calling itself when base
condition becomes True.
def gcd(a, b):
# base condition
def gcd(a, b):
if (b == 0):
while (b != 0):
return a
a=a%b
a, b = b, a
a=a%b
return a
a, b = b, a
return gcd(a, b) 123
Conversion between recursion and iteration

• To convert recursive function into iterative code,


• If the recursive function is tailed recursion (i.e., the
recursive function calls itself only once, and calling itself
and return in the last statement of the recursive
function), the conversion is straightforward.
• Example: the codes given in the previous slide
• If the recursive function is not tailed recursion, stack is
normally needed in the conversion
• For example, the recursive preorder traversal function is not
tailed recursion since it calls itself twice: 1) with left child as
input, 2) with right child as input.
Stack is needed when this recursive function is converted to
iterative function.

124
Summary
• Tree is useful for storing the data that naturally form hierarchy (such
as file system, decision tree)
• The binary search tree and AVL tree (will learn later) are useful for
storing and searching dynamic data
• Tree Traversal
• Depth-first traversal
• Preorder, Inorder, Postorder traversal
• Implemented using recursive function or stack
• Breath-first traversal
• Level-order traversal
• Implemented using queue
• From the implementations of traversal, we realize that it is
important to choose the proper data structure when we solve a
computational problem; otherwise, it may be extremely difficult
(sometimes impossible) to develop the algorithm.

125
Programming Practice on Binary Tree

• At the following website, in the “category”, choose “binary


tree” for the exercises:
https://www.techiedelight.com/data-structures-and-algorithms-
problems/

126

You might also like