Tree Part-II
Tree Part-II
CSC211
Lecture # 26
Representation of Trees
List Representation
– ( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) )
– The root comes first, followed by a list of sub-trees
B C
E
F G D
K L
H ( shows left
, shows right
M I
J
Binary Tree Representations in Array
If a complete binary tree with n nodes (depth = log2 (n + 1)-1) is
represented sequentially, then for any node with index i where
1<=i<=n, we have:
parent(i) is at i/2 if i!=1.
If i=1, i is at the root and has no parent.
left_child(i) is at 2i if 2i<=n.
If 2i>n, then i has no left child.
H I
Tree using Linked List Representation
struct node {
int data;
node* left; data
node* right;
};
left_child right_child
B C D
E F G H I J
K L M
37
t
6 Tree root node
t
2 8 NULL NULL 6
2 8
t
1 NULL NULL 4 NULL 1 4
3 5
New Node
Linked List Representation of Binary Tree
• Double linked list is used to represent a binary tree.
• Most clear representation is:
Binary Search Tree
7. The new node is made the left child of the root node if
the second number is less than the one in the root.
14
15 14
14
15
4 14
15
14
4 15
9 14
4 15
14
4 15
7 14
4 15
14
4 15
18 14
4 15
14
4 15
9 18
3 14
4 15
9 18
14
4 15
3 9 18
5 14
4 15
3 9 18
14
4 15
3 9 18
16 14
4 15
3 9 18
14
4 15
3 9 18
7 16
4 14
4 15
3 9 18
7 16
20 14
4 15
3 9 18
7 16
14
4 15
3 9 18
7 16 20
17 14
4 15
3 9 18
7 16 20
17, 9, 14, 5
Searching for Duplicates
14
4 15
3 9 18
7 16 20
5 17
17, 9, 14, 5
Searching for Duplicates
14
4 15
3 9 18
7 16 20
5 17
9, 14, 5