Professional Documents
Culture Documents
Tree
in
Data Structure
1
DATA STRUCTURE
Shawon(CTO ) Tarun(Presedent)
Shawon(CTO ) Tarun(Presedent)
5
RELATION OF TREE
2
Children
3
Parents
Siblings- Have same parents. 4 5 7
6 8
Leaf- Has no Child.
9 10 11
6
EDGES, DEPTH, HEIGHT
Leaf
7
SOME APPLICATION OF TREE IN COMPUTER SCIENCE
9
NULL
STRICT/PROPER BINARY TREE
Root
10
COMPLETE BINARY TREE
Root
L-1
L-2
11
L-4
PARFECT BINARY TREE
Root
L-1
L-2
12
WE CAN IMPLEMENT BINARY TREE USING
2 4 1 5 8 7 9
0 1 2 3 4 5 6
B) Arrays: It only works “complete Binary tree”.
For node at index i;
Left-child-index=2i+1
Right-child-index=2i+2 14
IMPLEMENT OF BINARY SEARCH TREE
15
Left-Subtree Right-Subtree
(Lesser) (Greater)
EXAMPLE
Root
15
15>10-Left
10 20
15<20-Right
10>8-Left
10<12-Right 8 12 17 25
20>17-Left
20<25-Right 16
BINARY TREE TRAVERSAL
F,D,J,B,E,G,K,A,C,I,H
B E G K
Depth-first
Preorder, Inorder & A I
C
Postorder 17
H
PREORDER(DLR)
Data Left Right
Root
F
<root><left><right>
F,D,B,A,C,E,J,G,I,H,K D J
Void Postorder(struct bstnode* root)
{
if(root==NULL)
B E G K
Postorder(root->right);
Postordrt(root->right);
A C I
printf(“%c”,root->data); 18
} H
INORDER(LDR)
Root
Left Data Right
F
<left><root><right> D J
A,B,C,D,E,F,G,H,I,J,K
Void Inorder(struct bstnode* root)
{
B E G K
if(root==NULL) return;
Inorder(root->left);
A C I
printf(“%c”,root->data);
19
Inorder(root->right);
} H
POSTORDER(LRD)
Left Right Data
Root
F
<left><right><root>
A,C,B,E,D,H,I,G,K,J,F,A,B D J
Void Postorder(struct bstnode* root)
{
if(root==NULL) B E G K
Postorder(root->right);
Postordrt(root->right); I
A C
printf(“%c”,root->data); 20
} H
SEARCH AN ELEMENT IN BST
Root
bool Search( bstnode* root, data type) 12
{
if (root==NULL) return false; 5 15
else if(root->data == data) return true;
else if(root->data <= data)
return Search(root->left, data); 3 7 13 17
else
return Search(root->right, data);
} 21
8 11 14
DLELETE A NODE FROM BST
Root
12
5 15
There are three items to delete.
Case 1: No Child
Case 2: One Child 3 7 13 17
5 15
23
8 11 14
CASE 2: ONE CHILD
Root
12
5 15
Find the Node to Delete
Link it’s parent to this only child.
Remain attached to the tree. 3 7 13 17
24
8 11 14
CASE 3: TWO CHILD
Root
12
1.
Find minimum in right
3 7 13 17
Copy the value in targetted node
Delete duplicate from right subtree.
25
8 11 14
CASE 3: TWO CHILD
Root
12
5 15
2.
Find maximum in left
Copy the value in targetted node 3 7 13 17
element x.
28