UNIT III Trees. Syllabus Difference in linear and non-linear data structure Trees and binary...

Preview:

Citation preview

UNIT III

Trees

2

SyllabusDifference 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

3

Non Linear DSLinear 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

4

Difference in Linear and Non-linear Data Structures

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

6/1/2014

5

Concept of tree data structureTree 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

F

B C D

E

6

Tree TerminologyNode: information

Edges: branches

Root A root is always at the top of

the tree. The root is A.

Parent It is immediate predecessor of

node. A is parent of B,C,D

Child It is immediate successors of

node. B,C,D are children of A.

A

F

B C D

E

7

Tree TerminologyLeaf Node

Siblings Nodes with same parent are

sibling. B,C,D are siblings

Descendent

Ancestors

Path It is no of successive edges

from sour to dest. Path from A to E is A-B,B-E

A

F

B C D

E

8

Degree of Node

The degree of a node is a no. of children of a node.

Leaf node is terminal node & has

no children.Degree 2

Degree 0

9

Height (or depth) of a tree The depth of a tree is the maximum depth of any of its leaves

tree depth = 3

tree depth = 2

tree depth = 0

Root

Root

10

ForestCollection of trees is known as Forest

When we remove root from tree, we get Forest

Original Tree

Root

Root removed

New roots

Forest

11

Binary TreeA 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

D

A

F

B

E E

12

13

Left skewed binary tree Right skewed binary tree Complete binary tree Strictly binary tree Full binary tree

Types of Binary Trees

14

LEFT SKEWED

Every intermediate node is the left child of its root

A

C

D

B

15

RIGHT SKEWED

Every intermediate node is the right child of its root

A

B

C

D

16

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

17

• Example :• Expression

18

•  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

Complete Binary Tree

19

•  Every node has two children, so that there are 2d nodes at level d. 

Full Binary Tree

20

A

E

B C

D

1

32

4 5 F7

0 1 2 3 4 5 6 7

7 A B C D E \0 F

Binary Tree representation using Array

No of Nodes : Index 0Root Node : Index 1Left Child: Parent Index * 2Right Child: Parent Index*2 + 1

21

22

23

Problems of array representation inefficient storage utilization ideal for complete binary trees hard to insert/delete

24

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

left_child right_child

data

25

Example: A

C

H

E F

I

GD

B

A

B C

0 E 0 0 F 0D 0 G 0

0 I 00 H 0

root

26

Implementationclass Tree{ struct Node{int Data;Node *Left,*Right};Node * Root;public:Tree() { Root=NULL;}void Insert();void Display();}

27

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

28

Binary tree traversalsvisit each node in the tree exactly oncewhat order?

inorder: LVR (Left Visit Right) preorder: VLR (Visit Left Right) postorder: LRV (Left Right Visit)

29

Recursivevoid inorderRec( Node *T)

{

if(T!=NULL)

{ inorderR(T->Left);

cout<<T->data;

inorderR(T->Right);

}

}

7/1/2014

30

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: }

}

31

Recursivevoid preorderR(node *T)

{

if(T!=NULL)

{

cout<<T->data;

preorderR(T->Left);

preorderR(T->Right);

}

}

8/1/2014

32

Recursivevoid postorderR(node *T)

{

if(T!=NULL)

{

postorderR(T->Left);

postorderR(T->Right);

cout<<T->data;

}

}

33

Expression Tree1. A+B*C

2. (A+B)*C

3. A+B+C

4. A*(B+C)-D/(E-F)

5. A*B+C-D/F

6. A+(B-C)*D$(E*F)

7. (A+B*C)$((A+B)*C)

8. (a+(b-c))*((d-e)/(f+g-h))

34

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-/*

35

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

36

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();

};

37

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(); }

38

9/1/2014

39

Non-recursive Inordervoid 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;

}

}

40

Non-recursive Preordervoid 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;

}

}

41

Non-recursive Postordervoid 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);

}

42

A General Tree

Convert general tree into Binary tree(leftmost child right sibling relation)

Convert forest into binary tree

13/1/2014

43

Example :

K

E F G H JI

B DC

A

L M

K

E F G H JI

B DC

A

L M

K

E

F G

H

J

I

B

D

C

A

L

M

Fig: Tree

left-child right-child tree representation of a tree

Binary tree

44

Create Binary tree1. Inorder: BAC Preorder:ABC

2. Inorder: DBEAFHG Preorder:ABDEHFG

3. Inorder:BACDEHFG Preorder:ECBADFHG

4. Inorder: QBKCFAGPEDHR Preorder:GBQACKFPDERH

5. Inorder:DFEGBCAIHKJL Preorder :ABDEFGCHIJKL

45

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

46

Create Binary Tree1. Inorder: BAC Postorder:BCA

2. Inorder: ABCDFEG Postorder: ACBFGED

3. Inorder: BACDEHFG Postorder: ABDCHGFE

4. Inorder: BCADFEHGI Postorder:CABFHIGED

5. Inorder: BACDEFGIHKJL

Postorder: ABDCFEIKLJHG

47

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+/$

BINARY SEARCH TREES

48

15/1/201416/1/2014

49

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

50

E.g.

1. 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

51

Operations on BSTInit

Create

Find/Search

Makeempty

Insert

Delete

Findmin

Findmax

52

BST as an ADTclass 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

53

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

};

54

Makeempty() void BST::Makeempty()

{

If(Root!=NULL)

{

Root=Root->Left;

Makeempty();

Root=Root->Right;

Makeempty();

Delete Root;

}

}

55

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');

}

56

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;

}

57

Else if(strcmp(Node->Info,Temp->Info)<0)

{

if(Temp->Left==NULL)

{ Temp->Left=Node; break;}

else Temp=Temp->Left;

}

}//while

}

}

58

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;

}

59

//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;

}

60

DFS//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];

}

}

18-1-2014

61

//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();

}

}

62

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;

63

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);

}

64

cout<<"\nHeight of Tree "<<Level-1;

cout<<“\nTotal No of Nodes"<<Count;

cout<<"\n Number of leaf Nodes "<<Leaf;

}

65

//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();

}

}

66

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;

67

}

else

{

cout<<" "<<Temp->Info<<" ";

if(Temp->Right!=NULL)

Queue[++Rear]=Temp->Right;

if(Temp->Left!=NULL)

Queue[++Rear]=Temp->Left;

}

}

}

68

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);

}

69

Delete

Leaf Node (Left & Right NULL)

One Child Node(Left or Right NULL)

Two Children Node(Left & Right not NULL)

70

Binary Search Tree(BST) Deleting a leaf or a node with 1 child

30

5

2

40

80

30

5

2

80

30

5

2

40

8035

(a) delete 35 (leaf) (b) delete 40 (node with single child)

71

Binary Search Tree(BST)

deletion of a node with two children

40

20

10

60

30 50 70

45 55

52

40

20

10

55

30 50 70

45 52

(a) tree before deletion of 60 (b) tree after deletion of 60

Threaded Binary Tree

73

TBTThere 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

74

TBT

8

75

3

11

13

1

6

9

75

Aroot

B C

GE

I

D

H

Fdangling

dangling

inorder traversal:H, D, I, B, E, A, F, C, G

TBT

76

1 1--

1 1A

1 1C1 1B

0 0E 0 0F 0 0G1 1D

0 0I0 0H

head

Memory Representation of TBT

root

77

Applications/Uses of treesTrees 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)

78

Thank You

Recommended