DFS (depth first search ) in BST (bindery search tree) in C++

DFS (depth first search) in binery search tree in C++
Code in Red highlighted area




#include<iostream.h>
#include<conio.h>
class Node{
private:
 int data;
 Node* right;
 Node* left;
public:
 Node(){
  root=NULL;
  right=left=NULL;
 }Node *root;

 void insert(int data){
  Node* newnode = new Node();
  newnode->data = data;
   if (root == NULL){
   root=newnode;
   return;
  }
  Node *p,*q;
  p=q=root;
  while (q!=NULL){
   p=q;
   if (newnode->data> q->data)
    q = q->right;
   else q = q->left;
  }
  if (newnode->data> p->data)
   p->right = newnode;
  else p->left = newnode;
 }


 void DFS(treenode *root,int value)
{

if(root!=NULL)
{
 cout<<"\t"<<root->getinfo();
if(root->getinfo()==value)
{ break;
DFS(root->getleft(),value);
DFS(root->getright(),value);
}
}

void inorder(treenode *root)
{
if(root!=NULL)
{
inorder(root->getleft());
cout<<"\t"<<root->getinfo();
inorder(root->getright());
}}

};

void main()
{
int c,A[]={8,4,5,1,12,11,13,3,14};
 Node b;
 clrscr();
 for(int i=0;i<=8;i++){
 b.insert(A[i]);
 }

 b.inorder(b.root);
 getch();

cout<<"\n\nEnter Value For Search ";
cin>>c;
b.DFS(b.root,c);
getch();


}


No comments

Powered by Blogger.