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

时间:2014-07-28 07:53:40

标签: c++ pointers reference binary-tree 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);
        }
    }

};

这是主要功能(不包括#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();

}

2 个答案:

答案 0 :(得分:5)

这不是指针的引用/取消引用,它是指向的引用。这是必要的,因为......

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

...您分配给参数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 // ...

答案 1 :(得分:0)

通过指针(没有引用),您将获得该地址的本地副本。这意味着你可以操纵指针后面的值(在这种情况下为* x),这会改变。但是,如果您更改地址本身,则地址将像本地副本一样,并且在离开方法后会丢失地址更改。