c++ - C++ 中的二叉树

标签 c++ binary-tree

我正在尝试用 C++ 实现一个二叉树,并以根-左-右的方式横穿它。添加所有节点后,我在这一行发生崩溃:

cout << r->st->st->info << endl; //trying to print root->left->left->info

我的 RSD 函数不打印任何内容。另外,如果有任何关于如何使用调试器的 Visual Studio 教程,我将不胜感激。谢谢。

#include<iostream>
using namespace std;

struct Nod{
    int info;
    Nod *st, *dr;
};

int read_tree(Nod *r)
{
    int info;
    cout << "Info: "; cin >> info;
    if (info!=0)
    {
        r = new Nod;
        r->info = info;
        read_tree(r->st);
        read_tree(r->dr);
    }
    else
        return 0;
}

void RSD(Nod *r)
{
    if (r != NULL)
    {
        cout << r->info << " ";
        RSD(r->st);
        RSD(r->dr);
    }
}

int main()
{
    Nod *r = NULL;
    read_tree(r);
    system("Pause");
    cout << r->st->st->info << endl;
    cout << r->dr->info;
    RSD(r);
}

最佳答案

问题是您将指针的拷贝传递给 read_tree 函数。也就是说,当您在 main 函数中调用 read_tree(r) 时,无论 read_tree< 内部发生了什么,r 都会保持为 NULL/功能。您可以通过引用传递指针来修复它。也就是说,将 read_tree(Nod* r) 更改为 read_tree(Nod*& r) 应该可以修复它。

关于c++ - C++ 中的二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28023614/

相关文章:

c++ - 在 std::exception 的扩展中调用 what() 后的字符串修改值

javascript - 尾递归二叉树搜索函数JS

c++ - 如何使用这个二叉树类?

树遍历应用

c++ - 如何从 2d Boost.MultiArray 中获取子数组?

c++ - 如何从 UserMode C++ 获取 ZwQuerySystemInformation 的地址

c++ - map 键没有可行的重载 '=' 错误

c++ - 调用::memalign 的代码无法在 g++ 4.8 中编译

c++ - 运算符重载的段错误

binary-tree - 关于完全二叉树