0

大家好,我真的很感谢任何帮助,谢谢。

首先,我正在构建一棵二叉树,但似乎无法构建它。在递归过程中,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;
}
4

1 回答 1

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 中节点的生命周期

于 2013-02-08T07:16:53.703 回答