PROGRAM TO COUNT SUM OF ALL NODES using RECURSION.
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
class B_Tree;
class Node
{
private:
int Info;
Node *Left, *Right;
friend class B_Tree;
};
class B_Tree
{
private:
Node *Root;
public:
B_Tree()
{
Root = NULL;
}
Node* Make_Root(int Value)
{
Node *Temp = new Node;
Temp->Info = Value;
Temp->Left = NULL;
Temp->Right = NULL;
return Temp;
}
void Make_Tree()
{
int No;
Node *P, *Q;
cout << "Enter Number To Make Root: ";
cin >> No;
cout << endl;
Root = Make_Root(No);
while(No != 25)
{
cout << "Enter Any Number: ";
cin >> No;
P = Q = Root;
while(P->Info != No && Q != NULL)
{
P = Q;
if(No < P->Info)
Q = P->Left;
else
Q = P->Right;
}
if(P->Info == No)
{
cout << "\nDuplicate Numbers Occurred...!!!\n" << endl;
exit(1);
}
else if(No < P->Info)
Set_Left(P, No);
else
Set_Right(P, No);
}
}
void Set_Left(Node *P, int Value)
{
if(P == NULL || P->Left != NULL)
{
cout << "\nCannot Insert On Left Of It...!!!\n" << endl;
exit(1);
}
P->Left = Make_Root(Value);
}
void Set_Right(Node *P, int Value)
{
if(P == NULL || P->Right != NULL)
{
cout << "\nCannot Insert On Right OF It...!!!\n" << endl;
exit(1);
}
P->Right = Make_Root(Value);
}
int Recursion_Sum(Node *P)
{
if(P == NULL)
return 0;
int Total = P->Info + Add(P->Left) + Add(P->Right);
return Total;
}
void Add_Sum()
{
cout << "\nSum Of All Nodes Is: " << Recursion_Sum(Root) << endl;
}
};
int main()
{
cout << "\t\t\tEnter 25 To End......" << endl;
B_Tree Obj;
Obj.Make_Tree();
Obj.Add_Sum();
getch();
return 0;
}
0 comments:
Post a Comment