Reputation: 149
hello all I really appreciate any help, thanks.
first off I am building a binary tree, but cant seem to build it. In the recursive process the insertHelper seems to recognize a larger root in first iteration, but then after does not continue build left and right and nodes connected to it. see in c++
header:
struct Node {
public:
int weight;
Node *right;
Node *left;
};
class Btree {
Node *root;
int insize;
int taxsize;
public:
Btree();
void insertOne(Node *);
void insertHelper(Node *, Node *);
void printTree();
void ptHelper(Node *);
};
class:
Btree::Btree() {
this -> root = NULL;
this -> insize =0;
this -> taxsize =0;
}
void Btree::insertOne( Node *n ) {
if(root==NULL) {
root = n;
}else {
Node *burr;
burr = root;
insertHelper( n, burr);
}
}
void Btree::insertHelper( Node *n, Node *curr ) {
if(curr==NULL) {
curr = n;
}
if(n->weight > curr->weight) {
insertHelper(n, curr->right);
}
if(n->weight < curr->weight) {
insertHelper(n, curr->left);
}
}
void Btree::printTree() {
Node *current;
current = root;
ptHelper(current);
}
void Btree::ptHelper(Node *m){
if(m != NULL) {
cout<<" "<<m->weight<<" ";
if(m->left != NULL) {
ptHelper(m->left);
}
if(m->right != NULL) {
ptHelper(m->right);
}
}else {
return;
}
}
main:
int main()
{
Btree joe;
int insize;
int taxsize;
cin >> insize;
for(int i=0; i<insize; i++) {
int tmp;
cin >> tmp;
Node *diamond = new Node();
diamond->weight = tmp;
joe.insertOne(diamond);
}
joe.printTree();
return 0;
}
Upvotes: 0
Views: 385
Reputation: 2442
You didn't update references to left and right. Try this:
void Btree::insertHelper( Node *n, Node *curr ) {
if(curr==NULL) {
curr = n;
}
//My debug output
//cout<<"InsertHelper "<<n->weight<< " to " << curr->weight <<" \n";
if(n->weight > curr->weight) {
if (curr->right == NULL) {
curr->right = n;
} else {
insertHelper(n, curr->right);
}
}
if(n->weight < curr->weight) {
if (curr->left == NULL) {
curr->left = n;
} else {
insertHelper(n, curr->left);
}
}
}
Note:
It's actually better to change interface to Btree::insertOne( int n )
. Then your can manage lifecycle of Nodes inside the BTree
Upvotes: 2