Professional Documents
Culture Documents
Lecture 8
TREES
• A data structure is said to be linear if its elements form a sequence or a linear
list. Previous linear data structures that we have studied like an array, stacks,
queues and linked lists organize data in linear order.
• A data structure is said to be nonlinear if its elements form a hierarchical
classification where, data items appear at various levels.
• Trees and Graphs are widely used non-linear data structures.
• Graphs are nothing but trees with certain restrictions removed.
TREES
TREES
• Tree and graph structures represents hierarchical
relationship that organizes data elements called nodes
by connecting them using links called edges.
a *
+ d
b c
• Depth : The number of edges from the node to the tree’s root node.
➢ Node C has a depth of 1.
• in-order (LVR):
17
41
6
41 9
17
81
9
6 81
TRAVERSAL EXAMPLE
Root
• pre-order (VLR): 17
17
41 41 9
6
9
6 81
81
TRAVERSAL EXAMPLE
Root
• post-order (LRV):
6 17
41
81 41 9
9
17 6 81
EXERCISE 1
– Pre-order: Root
42 15 27 48 9 86 12 5 3 39
42
– In-order:
15 9
15 48 27 42 86 5 12 9 3 39
27 86 3
– Post-order:
48 27 15 5 12 86 39 3 9 42 48 12 39
5
EXERCISE 2
EXAMPLE: EXPRESSION TREES
+
* +
a
a b
a++
a* b
EXAMPLE: C TREES
TREE IMPLEMENTATION
root
left A right