首页 > 解决方案 > 二叉树插入方法C++

问题描述

struct node {
    person * data;
    node * left, * right;

    node(person * p) {
        data = p; left = NULL; right = NULL;
    }
};

class tree {
    protected:
        node * root;
    public:
        tree() {
            root = NULL;
        }

        tree(person * p) {
            root = new node(p);
        }

        void insert(person * p) {
            if(root == NULL) {
                root = new node(p);
                return;
            }
            node * curr = root;
            while(true) {
                if(p->last < curr->data->last) {
                    if(curr->left == NULL) {
                        curr->left = new node(p);
                        return;
                    }
                    curr = curr->left;
                } else {
                    if(curr->right == NULL) {
                        curr->right = new node(p);
                        return;
                    }
                    curr = curr->right;
                }
            }
        }

        void insert(node * & n, person * p) {
            if(n == NULL) {
                n = new node(p);
                return;
            }
            if(p->last < n->data->last)
                insert(n->left, p);
            else
                insert(n->right, p);            
        }

        void insert(person * p) {
            insert(root, p);
        }
        void print(node * n) {
            if(n == NULL)
                return;
            print(n->left);
            cout << n->data->ss << " " << n->data->bday << " "<< n->data->first << ", " << n->data->last << " " << n->data->zip << "\n";
            print(n->right);
        }

        void print() {
            print(root);
        }
};

我查看了 BST 插入的其他实现,我的逻辑遵循我见过的其他线程。在构造函数中将 Root 设置为 NULL 当我使用 print 函数时,它会打印出随机值,而不是与 person 类型一起存储的信息。在我的代码中,我尝试了两种插入方法。我还包括了我的打印功能,以防出现问题。我从打印功能返回的打印输出几乎看起来像是显示内容的内存地址,但缺少一些信息。我不知道从这里去哪里。

标签: c++printingtreebinaryinsertion

解决方案


I found what the problem was. In my person struct, I was naming the parameters of the constructor the same as the variables in the struct. Apparently c++ doesn't like when that's done. Changing the names of the constructor parameters to something else fixed the problem.

Old:

person(int ssn, int bday, string first, string last, int zip) {
        ssn = ssn; bday = bday; first = first; last = llast; zip = zip; 
    }

New:

person(int s, int b, string f, string l, int z) {
        ssn = s; bday = b; first = f; last = l; zip = z; 
    }

推荐阅读