Tuesday, 4 December 2012

CS301 4th Assignment Solution



On Tue, Dec 4, 2012 at 9:16 PM, YASIR AWAN <yasirawan1992@gmail.com> wrote:
#include<iostream>
#include<conio.h>
using namespace std;


class BSTNode
{
public:
int number;
BSTNode* lpointer;
BSTNode* Rpointer;
bool Search(int number)
{
if (number==this->number)
{
return false;
}
else if(number< this->number)
{
if (lpointer==NULL)
{
lpointer=new BSTNode(number);
return true;
}
else
{
return lpointer->Search(number);
}
}
else if (number > this-> number)
{
if (Rpointer == NULL)
{
Rpointer = new BSTNode (number);
return true;
}
else
{
return Rpointer->Search(number);
}
}
return false;
}


BSTNode()
{}
BSTNode(int value)
{
this->number = value;
lpointer = NULL;
Rpointer = NULL;
}
};




class BST
{
private:
BSTNode* Root;
public:
BST()
{
Root = NULL;
count2 = 0;
count1 = 0;
}
int count1;
int count2;
void cout2Increment(int i)
{
count2+=1;
}
void cout1Increment(int i)
{
count1+=1;
}
int getCounter(int i)
{
int k;
if(i==1)
{
k= count1;
}
else
{
k=count2;
}
return k;
}
void Display();
void PreOrder(BSTNode*);
int TotalNodes();
int searchNode(BSTNode*);
int SearchLeaf();
int HelperLeaf(BSTNode*);

bool add(int number)
{
if (Root == NULL)
{
Root = new BSTNode(number);
return true;
}
else
{
return Root->Search(number);
}
}
};


int BST::SearchLeaf()
{
return HelperLeaf(Root);
}
int BST::HelperLeaf(BSTNode* pt)
{
if(pt !=NULL)
{
if (pt->Rpointer==NULL && pt->lpointer==NULL)
{
cout1Increment(1);
}
HelperLeaf(pt->lpointer);
HelperLeaf(pt->Rpointer);
}
return getCounter(1);
}
void BST::Display()
{
PreOrder(Root);
}
void BST::PreOrder(BSTNode* pt)
{
if (pt != NULL)
{
cout<<pt->number<<endl;
PreOrder(pt->lpointer);
PreOrder(pt->Rpointer);
}
else
{
return;
}
}
int BST::TotalNodes()
{
return searchNode(Root);
}
int BST::searchNode(BSTNode* pt)
{
if (pt != NULL)
{
cout2Increment(1);
searchNode(pt->lpointer);
searchNode(pt->Rpointer);

}
return getCounter(2);
}


main()
{
BST node;
int i=0;
int element[]={35,27,15,59,31,29,33,85,62,96,78};
while(i!=11)
{
int data=element[i];
if (node.add(data)==false)
{
cout<<"\nElement is Duplicated\n";
}
i=i+1;
}
cout<<"Displaying nodes values:\n"<<endl;
node.Display();

cout<<"Number of leaf nodes in the BST = "<<node.SearchLeaf()<<endl;
cout<<"Total number of nodes in the BST = "<<node.TotalNodes();
getch();
}

--
You received this message because you are subscribed to the Google
Groups "-VU-ROCKS-" group.
To post to this group, send email to VU-ROCKS@googlegroups.com
http://groups.google.com/group/VU-ROCKS?hl=en
 
 



--
-- 
For University of Pakistan Study Material Sharing, Discussion, etc, Come and join us at http://4e542a34.linkbucks.com
You received this message because you are subscribed to the Google
Groups "Study" group.
To post to this group, send email to http://ca13054d.tinylinks.co
For more options, visit this group at
http://004bbb67.any.gs


No comments:

Post a Comment

Note: only a member of this blog may post a comment.