需要引用和解除引用指向根的二叉树指针.为什么?

Raf*_*azZ 1 c++ binary-tree pointers reference dereference

我的问题是为什么我需要取消引用并引用以下代码的指针才能工作?不参考/反对取消吗?我真的很感激,如果有人能解释它,就像我五岁:)

码:

template <typename T> 
class binNode {
private:
    T key;
public:
    binNode * left;
    binNode * right;
    binNode * parent;
    binNode() {
        this->left = NULL;
        this->right = NULL;
        this->parent = NULL;
    }
    // arg constructor:
    binNode (T key) {
        this->key = key;
        this->left = NULL;
        this->right = NULL;
        this->parent = NULL;
    }

    T getKey() {
        return this->key;
    }
    void setKey(T key) {
        this->key = key;
    }
};

template<typename T> class Tree {
private:
    binNode <T> *root;
public:
    Tree() {
        this->root = NULL;
    }
    Tree(binNode <T> * node) {
        node->parent = NULL;
        this->root = node;
    }
    /* THIS IS THE PART I  DON'T GET */
    void addNode(binNode<T> *&x, binNode<T> * node) { // what's up with the *&???
        if (x == NULL) {
            x = node;
            return;
        } else if (x->getKey() == node->getKey()) {
            node->left = x;
            node->parent = x->parent;
            x->parent = node;
            return;
        }

        if (node->getKey() < x->getKey()) {
            addNode(x->left, node);
        } else {
            addNode(x->right, node);
        }

    }

    void addNode(binNode<T> * node) {
        addNode(this->root, node);
    }

    binNode<T> * treeSearch(binNode<T> * x, T key) {
        if (x == NULL || key == x->getKey()) {
            return x;
        }
        if (key < x->getKey()) {
            return treeSearch(x->left, key);
        } else {
            return treeSearch(x->right, key);
        }
    }

    void printOrdered() {
        inorderTreeWalk(root);
        cout << endl;
    }

    void inorderTreeWalk(binNode<T> * node) {
        if (node != NULL) {
            inorderTreeWalk(node->left);
            cout << node->getKey() << '\t';
            inorderTreeWalk(node->right);
        }
    }

};
Run Code Online (Sandbox Code Playgroud)

这是主要功能(#inlude不包括在内)

int main() {
    Tree<int> T (new binNode<int>(10));
    // Tree<int> T = new binNode<int>(10);

    T.addNode(new binNode<int> (11));
    T.addNode(new binNode<int> (9));
    T.addNode(new binNode<int> (8));
    T.addNode(new binNode<int> (12));

    T.printOrdered();

}
Run Code Online (Sandbox Code Playgroud)

Dev*_*lar 5

这不是一个引用/取消引用指针,这是一个参考,以一个指针.这是必要的,因为......

void addNode(binNode<T> *&x, binNode<T> * node) {
    if (x == NULL) {
        x = node; // ...here...
        return;
    } else // ...
Run Code Online (Sandbox Code Playgroud)

...您正在分配参数x.

如果您没有通过x 引用传递指针,则将分配给参数的本地副本:

void addNode(binNode<T> * x, binNode<T> * node) {
    if (x == NULL) {
        x = node; // this acts on the local copy only, and thus does nothing.
        return;
    } else // ...
Run Code Online (Sandbox Code Playgroud)