BST中的指针跟踪

时间:2019-04-11 07:36:02

标签: c++ pointers binary-search-tree

我想使用指针构建自己的BST。问题在于插入数据,可能问题在于该树中的“跟踪”。我是指针的新手,也许我错过了一些东西。

#include <iostream>

using namespace std;

struct tree {
    int data;
    tree * left;
    tree * right;

    void add(int data);
};
tree * root = NULL;

void tree::add(int data) {
    tree * tmp = new tree;
    tmp->data = data;
    tmp->left = NULL;
    tmp->right = NULL;

    if (root == NULL) {
        root = tmp;
    } 
    else if(root->data >= data) {
        tree * current = root;

        if (current->left == NULL) {
            current->left = tmp;
        } else {
            while (current->left != NULL || current->right != NULL) {
                if (data <= current->data) {
                    current = current->left;
                } else {
                    current = current->right;
                }
            }// problem is here
        }
    }
}

int main(){
    tree * tmp = new tree;

    tmp->add(100);
    tmp->add(60);
    tmp->add(50);
    tmp->add(90);
}

0 个答案:

没有答案