Download Trees - unit 1

Document related concepts
no text concepts found
Transcript
UNIT III
Trees
Syllabus
Difference in linear and non-linear data structure
Trees and binary trees-concept and terminology
Binary tree as an ADT.
Algorithm for tree traversals (recursive and non
recursive).
Conversion of general tree to binary tree.
Binary search trees,
Concept of threaded binary tree.
Threaded binary tree as an ADT.
Preorder, Inorder traversals of inorder threaded
binary tree
Applications of trees
2
Non Linear DS
Linear Data Structure :one to one relationship
To store info within the computer system having
a root directory , subdirectory & related fields
Linear DS: more space & time
Non linear DS: more complex relationship
3
Difference in Linear and Non-linear Data
Structures
6/1/2014
LINEAR DATA STRUCTURES
NON-LINEAR DATA STRUCTURES
Linear Data structures are used to represent
sequential data.
Non-linear data structures are used to
represent hierarchical data.
Linear data structures are easy to implement
These data structures are difficult to
implement.
Implementation: Linear data structures are
implemented using array and linked lists
Implementation: Non-linear data structures
are mostly implemented using linked lists.
e.g: The basic linear data structures are list,
stack and queue.
e.g: The basic non-linear data structures are
trees and graphs.
For the implementation of linear data
structures, we don’t need non-linear data
structures.
For the implementation of non-linear data
structures, we need linear data structures.
USE: These are mostly used in application
software development.
USE: These are used for the development of
game theory, artificial intelligence, image
processing
4
Concept of tree data structure
Tree data structure
 Definition: A tree
is a finite set of one or more nodes
such that
1. There is a specially designated node called the root.
2. The remaining nodes are partitioned into n>=0 disjoint sets
T1,….,Tn, where each of these sets is a tree. T1,…,Tn are
called the subtrees of the root.
A
B
E
C
D
F
5
Tree Terminology
Node: information
Edges: branches
Root
A
 A root
is always at the top of
the tree. The root is A.
B
D
C
Parent
 It
E
is immediate predecessor of
node. A is parent of B,C,D
F
Child
 It
is immediate successors of
node. B,C,D are children of A.
6
Tree Terminology
Leaf Node
Siblings
A
 Nodes
with same parent are
sibling. B,C,D are siblings
Descendent
Ancestors
Path
E
B
D
C
F
 It
is no of successive edges
from sour to dest. Path from A
to E is A-B,B-E
7
Degree of Node
The degree of a node is a no. of children of a
node.
Leaf node is terminal node & has
Degree 2
no children.
Degree 0
8
Height (or depth) of a tree
The depth of a tree is the maximum depth of any of its
leaves
Root
Root
tree depth = 3
tree depth = 2
tree depth = 0
9
Forest
Collection of trees is known as Forest
When we remove root from tree, we get Forest
Root
New roots
Root removed
Forest
Original Tree
10
Binary Tree
A tree is binary if each node of the tree can have
maximum of two children
Outgoing Degree : 0 , 1 , 2
Its Empty tree or finite set of nodes
Subtrees: Left & Right subtree
A
D
B
E
F
E
11
12
Types of Binary Trees





Left skewed binary tree
Right skewed binary tree
Complete binary tree
Strictly binary tree
Full binary tree
13
LEFT SKEWED
Every intermediate node is the left child of
its root
A
B
C
D
14
RIGHT SKEWED
Every intermediate node is the right
child of its root
A
B
C
D
15
Strictly Binary Tree
•
If every non leaf node in a binary tree has non empty left
and right subtrees, the tree is termed as a strictly binary
tree. A node will have either two children or no child at
all
16
•
Example :
• Expression
17
Complete Binary Tree
•
binary tree in which every level, except possibly the
last, is completely filled, and all nodes are as far left as
possible
•
A complete binary tree is define as binary tree where
 All of its leaves or terminal nodes are on level (n-1) or n
 Leaves are filled from left to right
18
Full Binary Tree
•
Every node has two children, so that there are
2d nodes at level d.
19
Binary Tree representation using
Array
No of Nodes : Index 0
Root Node : Index 1
Left Child: Parent Index * 2
Right Child: Parent Index*2 + 1
1
A
3
C
2
B
4
D
5
E
F
0
1
2
3
4
5
6
7
7
A
B
C
D
E
\0
F
7
20
21
22
Problems of array representation

inefficient storage utilization
 ideal for complete binary trees
 hard to insert/delete
23
Binary Tree using Linked List
Linked Representation of binary tree is more
efficient than array representation
typedef struct node
{
int data;
struct node *left,*right
};
left_child data right_child
data
left_child
right_child
24
Example:
A
B
D
H
C
E
F
root
G
I
A
B
C
D
0
H 0
0
0
I
E
0
0
F
0
0
G 0
0
25
Implementation
class Tree
{
struct Node
{
int Data;
Node *Left,*Right
};
Node * Root;
public:
Tree() { Root=NULL;}
void Insert();
void Display();
}
26
void Tree::Insert( int Num)
{
Node *nNode=new Node;
nNode->Data=Num;
nNode->Left=nNode->Right=NULL;
While( 1 )
{
cout<<“Enter Direction( L/R)”;
cin>>Direction;
if(Direction== ‘L’)
{
if(Temp->Left== NULL)
{ Temp->Left=nNode;
break;}
else
Temp=Temp->Left;
}//
else//insert at right
{
if(Temp->Right== NULL)
{ Temp->Right=nNode;
break;}
else
Temp=Temp->Right;
}
}//while ( 1 )
}//end of Insert
27
Binary tree traversals
visit each node in the tree exactly once
 what order?
 inorder: LVR (Left Visit Right)
 preorder: VLR (Visit Left Right)
 postorder: LRV (Left Right Visit)
28
Recursive
7/1/2014
void inorderRec( Node *T)
{
if(T!=NULL)
{ inorderR(T->Left);
cout<<T->data;
inorderR(T->Right);
}
}
29
How system stack work?
void inorderRec(Node *T)
{
1001: if(T!=NULL)
1002: {
1003: inorderR(T->Left);
1004: cout<<T->data;
1005: inorderR(T->Right);
1006: }
}
30
Recursive
8/1/2014
void preorderR(node *T)
{
if(T!=NULL)
{
cout<<T->data;
preorderR(T->Left);
preorderR(T->Right);
}
}
31
Recursive
void postorderR(node *T)
{
if(T!=NULL)
{
postorderR(T->Left);
postorderR(T->Right);
cout<<T->data;
}
}
32
Expression Tree
1.
2.
3.
4.
5.
6.
7.
8.
A+B*C
(A+B)*C
A+B+C
A*(B+C)-D/(E-F)
A*B+C-D/F
A+(B-C)*D$(E*F)
(A+B*C)$((A+B)*C)
(a+(b-c))*((d-e)/(f+g-h))
33
Convert Postfix Expression to Binary
Tree
1. ABC*+
2. AB+C*
3. AB+C+
4. ABC+*DEF-/5. AB* C+DF/6. ABC-DEF*$*+
7. ABC*+ AB+C*$
8. abc-+ de-fg+h-/*
34
Convert Prefix Expression to Binary
Tree
1. +A*BC
2. *+ABC
3. ++ABC
4. -*A+BC/D-EF
5. -+*ABC/DF
6. +A*-BC$D*EF
7. $+A*BC*+ABC
8. *+a-bc/-de-+fgh
35
struct Tree
{ char Data; struct Tree *Left,*Right;
Tree(char D='\0'){ Data=D; Left=Right=NULL;}
};//Structure for Expression
class Stack
{
Tree *Stk[20]; int Top;
public:
Stack(){Top=-1;}
int isEmpty();
int isFull();
void Push(Tree*);
Tree* Pop();
};
36
Tree *Create()
{ char Estr[25]; int I=0; Stack S;
cout<<"Enter Postfix Expression“; cin>>Estr;
while(Estr[I]!='\0')
{
Tree *Node=new Tree(Estr[I]);
if(isalnum(Estr[I])) S.Push(Node);
else
{ Node->Right=S.Pop();
Node->Left=S.Pop();
S.Push(Node);
}
I++;
}
return S.Pop(); }
37
9/1/2014
38
Non-recursive Inorder
void NonRin(Tree *Root)
{
Stack S;
while(!S.isEmpty()||Root!=NULL)
{
while(Root!=NULL)
{
S.Push(Root);
Root=Root->Left;
}
Root=S.Pop();
cout<<Root->Data;
Root=Root->Right;
}
}
39
Non-recursive Preorder
void NonRpre(Tree *Root)
{
Stack S;
while(!S.isEmpty()||Root!=NULL)
{
while(Root!=NULL)
{
cout<<Root->Data;
S.Push(Root);
Root=Root->Left;
}
Root=S.Pop();
Root=Root->Right;
}
}
40
Non-recursive Postorder
void NonRpost(Tree *Root)
{
Stack S; int I=0; char Str[25];
while(!S.isEmpty()||Root!=NULL)
{
while(Root!=NULL)
{
Str[I++]=Root->Data;
S.Push(Root);
Root=Root->Right;
}
Root=S.Pop();
Root=Root->Left;
}
Str[I]='\0';
cout<<strrev(Str);
}
41
A General Tree
13/1/2014
Convert general tree into Binary tree(leftmost
child right sibling relation)
Convert forest into binary tree
42
A
Example :
B
E
K
C
F
G
L
D
H
I
J
M
A
Fig: Tree
A
B
E
B
C
K
F
L
G
C
D
K
E
Binary tree
H
I
J
F
G
L
left-child right-child tree
M representation of a tree
D
H
M
I
J
43
Create Binary tree
1.
Inorder: BAC
Preorder:ABC
2.
Inorder: DBEAFHG
Preorder:ABDEHFG
3.
Inorder:BACDEHFG
Preorder:ECBADFHG
4.
Inorder: QBKCFAGPEDHR
Preorder:GBQACKFPDERH
5.
Inorder:DFEGBCAIHKJL
Preorder :ABDEFGCHIJKL
44
6. Inorder: A*B-C+D*E/F
Preorder: +*A-BC/*DEF
7. Inorder: A*B/C$D*E-F$G+H
Preorder: $/*ABC-*DE+$FGH
8.
Inorder: A$C*D/E+F-G*H
Preorder: /$A*CD+E-F*GH
45
Create Binary Tree
1.
Inorder: BAC
Postorder:BCA
2.
Inorder: ABCDFEG
Postorder: ACBFGED
3.
Inorder: BACDEHFG
Postorder: ABDCHGFE
4.
Inorder: BCADFEHGI
Postorder:CABFHIGED
5.
Inorder: BACDEFGIHKJL
Postorder: ABDCFEIKLJHG
46
6.
Inorder: A+B-C*D$E*F
Postorder:ABC-DEF*$*+
7.
Inorder: A+B-C$D+E-F*G$H
Postorder: ABC-D$*EFG*H$-+
8.
Inorder: A*B-C$D/E+F
Postorder: ABC-*DEF+/$
47
15/1/2014
16/1/2014
BINARY SEARCH TREES
48
Binary Search Tree(BST)
Binary search tree(BST) is a binary tree that is
empty or each node satisfies the following
properties:
1) every element has a key, and no two elements have
the same key
2) the keys in a nonempty left subtree must be smaller
than the key in the root of the subtree
3) the keys in a nonempty right subtree must be larger
than the key in the root of the subtree
4) the left and right subtrees are also BST
49
1.
E.g.
14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5
2.
18, 5, 9, 19, 4, 3, 30, 16, 7, 26, 4, 25, 2, 35
3.
10, 5, 8, 25, 4, 18, 13, 9, 1, 3, 12
4.
80, 90, 45, 60, 115, 78, 92, 69, 70, 35, 22, 145,
96, 55, 82
50
Operations on BST
Init
Create
Find/Search
Makeempty
Insert
Delete
Findmin
Findmax
51
BST as an ADT
class BST
{
struct BSearchT
{ char Info[10]; BSearchT *Left,*Right;
BSearchT(){ Left=Right=NULL; }
} *Root;
public:
BST(){Root=NULL;}//init
void Makeempty(); // make tree empty
void Create();
void Insert(char*); //Binary Search Tree Creation
int Search(char *);//Non Recursive Search
int Rsearch(char *); //Recursive Search
52
void DFS();//Depth First Search Non Recursive
void RDFS();//Depth First Search Recursive
void BFS();//Breath First Search Non Recursive(Levelwise Display)
//Count Number of Node,No of Leaf Node & Height of the
Tree
void BST::RBFS();//Breath First Search Recursive
void Mir_RBFS(); //Display Mirror image of Tree Recursively
void mirror(); //Display Mirror image of Tree Non Recursive
void mir_BFS(); //Non Recursive Mirror Image
void R_mir() //Mirror Image Recursive
BSearchT * Dsearch(char *M) //Delete Node
BSearchT *Tree_copy() //Tree Copy
};
53
Makeempty()
void BST::Makeempty()
{
If(Root!=NULL)
{
Root=Root->Left;
Makeempty();
Root=Root->Right;
Makeempty();
Delete Root;
}
}
54
Create
//create tree
void BST::Create()
{
char Str[10],ans;
do
{
cout<<"Enter String";
cin>>Str;
Insert(Str);
cout<<"\nAdd More...(Y/N)";
cin>>ans;
}while(ans=='y' || ans=='Y');
}
55
insert
//Binary Search Tree Creation
void BST::Insert(char* String)
{
BSearchT *Node,*Temp;
Node=new BSearchT; strcpy(Node->Info,String);
if (Root==NULL) Root=Node;
else { Temp=Root;
while(1)
{
if(strcmp(Node->Info,Temp->Info)>0)
{
if(Temp->Right==NULL)
{Temp->Right=Node; break;}
else Temp=Temp->Right;
}
56
Else if(strcmp(Node->Info,Temp->Info)<0)
{
if(Temp->Left==NULL)
{ Temp->Left=Node; break;}
else Temp=Temp->Left;
}
}//while
}
}
57
Search
//Non Recursive Search
int BST::Search(char *M)
{
int Flag=0; BSearchT *Temp=Root;
while(Temp!=NULL)
{
if(strcmp(M,Temp->Info)>0)
Temp=Temp->Right;
else if(strcmp(M,Temp->Info)<0)
Temp=Temp->Left;
else { Flag=1;break;}
}
return Flag;
}
58
//Recursive Search
int BST::Rsearch(char *M)
{
static int Flag=0;
static BSearchT *Temp=Root;
if(Temp!=NULL)
{
if(strcmp(M,Temp->Info)>0)
{ Temp=Temp->Right;Rsearch(M);}
else if(strcmp(M,Temp->Info)<0)
{ Temp=Temp->Left; Rsearch(M);}
else Flag=1;
}
return Flag;
}
59
DFS
18-1-2014
//Depth First Search Non Recursive
void BST::DFS()
{
BSearchT *Stack[20],*Temp=Root; int Top=-1;
while(Temp!=NULL || Top > -1)
{
cout<<Temp->Info;
if(Temp->Right!=NULL)
Stack[++Top]=Temp->Right;
Temp=Temp->Left;
if(Temp==NULL)
Temp=Stack[--Top];
}
}
60
//Depth First Search Recursive
void BST::RDFS()
{
static BSearchT *Temp=Root;
if(Temp!=NULL)
{
cout<<Temp->Info;
Temp=Temp->Left;
RDFS();
Temp=Temp->Right;
RDFS();
}
}
61
BFS
//Breath First Search Non Recursive(Level wise Display)
//Count Number of Node, No of Leaf Node & Height of the Tree
void BST::BFS()
{
BSearchT *Queue[20],*Temp=Root;
int Front=0,Rear=1,Level=-1,Count=0,Leaf=0;
if(Temp==NULL)
cout<<"\nEmpty Temp";
else
{
Queue[0]=Temp;
Queue[1]=NULL;
cout<<"\nLevel "<<++Level;
62
do
{ Temp=Queue[Front++];
if(Temp==NULL)
{ Queue[++Rear]=NULL; cout<<"\nLevel "<<++Level; }
else
{ Count++;//Total Number of Nodes in a Tree
cout<<" "<<Temp->Info<<" ";
if(Temp->Left!=NULL) Queue[++Rear]=Temp->Left;
if(Temp->Right!=NULL) Queue[++Rear]=Temp->Right;
else if(Temp->Right==NULL && Temp->Left==NULL)
Leaf++;//Number of Leaf Nodes
}
}while(Front<Rear);
}
63
cout<<"\nHeight of Tree "<<Level-1;
cout<<“\nTotal No of Nodes"<<Count;
cout<<"\n Number of leaf Nodes "<<Leaf;
}
64
//Breath First Search Recursive
void BST::RBFS()
{
static int Front=0,Rear=0;
static BSearchT *Queue[10],*Temp=Root;
if(Front<=Rear)
{ cout<<" "<<Temp->Info<<" ";
if(Temp->Left!=NULL) Queue[Rear++]=Temp->Left;
if(Temp->Right!=NULL) Queue[Rear++]=Temp->Right;
Temp=Queue[Front++];
RBFS();
}
}
65
Display Mirror
//Display Mirror image of Tree Non Recursive
void BST::mirror()
{
struct BSearchT *Queue[20],*Temp=Root;
int Front=0,Rear=1;
Queue[0]=Temp; Queue[1]= NULL;
while(Front<Rear)
{
Temp=Queue[Front++];
if(Temp==NULL)
{ cout<<"\n";
Queue[++Rear]=NULL;
66
}
else
{
cout<<" "<<Temp->Info<<" ";
if(Temp->Right!=NULL)
Queue[++Rear]=Temp->Right;
if(Temp->Left!=NULL)
Queue[++Rear]=Temp->Left;
}
}
}
67
Change to Mirror
//Non Recursive Mirror Image
void BST::mir_BFS()
{
struct BSearchT *Queue[20],*Temp1,*Temp=Root; int Front=0,Rear=1;
Queue[0]=Temp;
do
{
Temp=Queue[Front++];
Temp1=Temp->Left;
Temp->Left=Temp->Right;
Temp->Right=Temp1;
if(Temp->Left!=NULL)
Queue[Rear++]=Temp->Left;
if(Temp->Right!=NULL) Queue[Rear++]=Temp->Right;
}while(Front<Rear);
}
68
Delete
 Leaf Node (Left & Right NULL)
 One Child Node(Left or Right NULL)
 Two Children Node(Left & Right not NULL)
69
Binary Search Tree(BST)

Deleting a leaf or a node with 1 child
30
5
2
40
35
80
30
5
30
40
2
5
80
(a) delete 35 (leaf)
80
2
(b) delete 40 (node with single child)
70
Binary Search Tree(BST)
40
40
20
10
60
30
50
45
20
70
10
55
30
55
50
45
70
52
52
(a) tree before deletion of 60
 deletion
(b) tree after deletion of 60
of a node with two children
71
Threaded Binary Tree
TBT
There are more null links than actual pointers in
representation of any binary tree
n+1 null links out of 2n total links
How to use the null links?
Replace the null links by pointers, called
threads, to other nodes in the tree
73
TBT
6
8
3
1
5
7
11
9
13
74
TBT
root
A
dangling
C
B
dangling
H
E
D
I
F
G
inorder traversal:
H, D, I, B, E, A, F, C, G
75
Memory Representation of TBT
head
1
--
1
root
1
A
1
B
1
D
1
0
H
0
E
0
1
0
I
C
1
1
0
0
F
0
1
0
G
0
0
76
Applications/Uses of trees
Trees are used in computer programming.
They can be used for improving database search
times. (e.g. binary search trees, AVL trees, red-black
trees).
Game programming(minmax trees, decision trees,
path finding trees)
Graphics programming (BSP trees, Quadtrees,
octrees)
Arithmatic scripting languages (arithmatic
precedence trees)
Data compression (Huffman trees)
File systems (B-trees, sparse indexed trees, trie trees)
77
78
Related documents