二叉树递归添加不产生正确的结果

时间:2014-06-23 18:10:33

标签: c++ binary-search-tree

我正在为练习编写一个二叉搜索树,我的递归添加有问题。我的迭代添加似乎工作正常,我的打印也是如此,但只要我使用addRecursive向我的树添加20和25,就没有添加似乎可以完成。

这对我来说有点令人费解。任何帮助将得到赞赏以及当然的解释。

#include <iostream>

using namespace std;

class Node {

    public: 
        int value;
        Node * left;
        Node * right;
        Node (int v, Node * l = 0, Node * r = 0) : value (v){}

};

class Tree {

    public:
        Node * top;

        Tree(){
            top = 0;
        }

        Tree (int value){
            top = new Node(value);
        }

        void add(int value);
        void addRecursive(Node * node, int value);
        void print(Node * node);
        void root();
};

void Tree::add(int value){
    if (top == NULL){
        top = new Node(value);
        return;
    }
    Node * newNode = new Node(value);
    Node * current = top;
    bool added = false;
    while (!added){
        if (value < current->value){
            if (current->left == NULL){
                current->left = newNode;
                added = true;
            }
            else {
                current = current->left;
            }
        }
        else if (value >= current->value){
            if (current->right == NULL){
                current->right = newNode;
                added = true;
            }
            else{
                current = current->right;
            }
        }
    }
}

void Tree::addRecursive(Node * node, int value){
    if (node == NULL){
        node = new Node(value);
    }
    else{
        if (value < node->value){
            addRecursive(node->left, value);
        }
        else if (value >= node->value){
            addRecursive(node->right, value);
        }
    }
    return;
}

void Tree::print(Node * node){
    if (node == NULL){
        return;
    }
    print(node->left);
    cout << node->value << " ";
    print(node->right);
}

int main(){
    Tree * tree = new Tree();
    tree->add(5);
    tree->print(tree->top);
    cout << endl;
    cout << "------------" << endl;
    tree->add(10);
    tree->add(15);
    tree->print(tree->top);
    cout << endl;
    cout << "------------" << endl;
    tree->addRecursive(tree->top, 20);
    tree->addRecursive(tree->top, 25);
    tree->print(tree->top);
}

1 个答案:

答案 0 :(得分:4)

void Tree::addRecursive(Node * node, int value){
    if (node == NULL){
        node = new Node(value);
    }

node这里是您放入的指针的副本。您创建一个新节点并将其分配给此副本,而不是要插入的tree->top