二叉树根为空

时间:2015-09-10 02:35:10

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

我正在尝试创建一个二叉搜索树,但它似乎没有工作。我调试了它,它说root是null。我不明白为什么它是null。我最初在构造函数中将它设置为null,但是当我调用insert()方法时,它不再为null,对吧?有人可以帮助我理解这一点。感谢。

#include "stdafx.h"
    #include <iostream>

using namespace std;


struct node
{
public:
    int value;
    node * left;
    node * right;
};


class bTree
{
public:
    node * root;

public:
    bTree();
    void insert(node * r, int val);
    void insert(int val);
    void traversePreorder();
    void traversePreorder(node * r);


};

bTree::bTree()
{
    root = NULL;
}

void bTree::insert(node * r, int val)
{
    if (r == NULL)
    {
        r = new node();
        r->value = val;
        r->left = NULL;
        r->right = NULL;
        return;
    }
    else
    {
        if (val <= r->value)
        {
            insert(r->left, val);
        }
        else
        {
            insert(r->right, val);
        }
    }
}

void bTree::insert(int val)
{
    insert(root, val);
}

void bTree::traversePreorder(node * r)
{
    if (root == nullptr)
        return;
    else
    {
        cout << root->value << " ";
        traversePreorder(root->left);
        traversePreorder(root->right);
    }
}

void bTree::traversePreorder()
{
    traversePreorder(root);
}

int main()
{
    bTree * myTree = new bTree();

    myTree->insert(30);

    myTree->insert(40);
    myTree->insert(20);
    myTree->insert(10);
    myTree->insert(50);


    myTree->traversePreorder();

    return 0;
}

1 个答案:

答案 0 :(得分:2)

如果你调试到void bTree::insert(node * r, int val),你会发现root根本没有改变。

void bTree::insert(node * r, int val)中,r按值传递,因此函数内部r的更改(new等)与外部变量无关({ {1}})。您可以将其更改为通过引用传递:

root

What's the difference between passing by reference vs. passing by value?
How to pass objects to functions in C++?

顺便说一句:在void bTree::insert(node *& r, int val) 中,您应该使用void bTree::traversePreorder(node * r),而不是r

root

LIVE