### Tree using Classes Problem

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151`` `````` #include using namespace std; struct node{ int data; node *large; node *small; }; class bst{ public: bst(); void add(int x); bool isempty(); node *getroot(); void print(node *p); int max(); int min(); int total(node *p); private : node *root; }; bst::bst() { root=NULL; } bool bst::isempty() { return(root==NULL); } void bst::add(int x) { node*cur=root,*trail,*ptr; ptr=new node; ptr->data=x; ptr->large=NULL; ptr->small=NULL; if(isempty()) { root=ptr; } else{ while(cur!=NULL) { trail=cur; if (cur->data== x) { cout << "The item is already in the tree \n"; system("PAUSE"); return; } else if(cur->data>x) cur=cur->small; else cur=cur->large; } if(trail->data>x) trail->small=ptr; else trail->large=ptr; } } node* bst::getroot() { return root; } void bst::print(node *p) { if(p!=NULL) { print(p->small); cout<data<<" "; print(p->large); } } int bst:: max() { node *cur=root; while(cur->large!=NULL) cur=cur->large; return cur->data; } int bst::min() { node *cur=root; while(cur->small!=NULL) cur=cur->small; return cur->data; } int bst::total(node *p) { static int sum1=0; static int sum2=0; node *cur=root; while(cur->large!=NULL){ sum1=sum1+cur->data; cur=cur->large;} cur=root; while(cur->small!=NULL){ sum2=sum2+cur->data; cur=cur->small; } return sum2+sum1+root->data; } int main() { int x; bst tree; int y; cout<<"please enter a number "<>x; while(x>0) { y=x%10; x=x/10; tree.add(y); } tree.print(tree.getroot()); cout<
It is not working because you have not properly iterated the tree. You have simply calculated the sum of the outer nodes of the tree, the inner nodes still have to be accounted for.

Hint: How is your print function displaying all nodes?
Well, The print Function is by Recursion. i had thought about using recursion. i will try using recursion. Thank you.
i had solve it using this method:

[output][int main()
{
int x;
bst tree;
int y;
cin>>x;
int sum=0;
while(x>0)
{
y=x%10;
sum=sum+y;
x=x/10;
}

tree.print(tree.getroot());
cout<<endl;

cout<<"the max is "<<tree.max()<<endl;
cout<<"The min is "<<tree.min()<<endl;
cout<<"the sum is"<<sum<<endl;

system("pause");
return 0;
}

/output]
Topic archived. No new replies allowed.