大家好,我非常感谢任何帮助,谢谢。
首先我正在构建一个二叉树,但似乎无法构建它。在递归过程中,insertHelper似乎在第一次迭代中识别出更大的根,但之后不继续构建左右,并且节点连接到它。看到 在c ++中
头:
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 *);
};
类:
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;
}
}
主:
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;
}
答案 0 :(得分:2)
您没有更新左右参考。 试试这个:
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);
}
}
}
注意:
将界面更改为Btree::insertOne( int n )
实际上更好。然后你可以在BTree中管理节点的生命周期