简体   繁体   English

C ++中的二叉树

[英]Binary Tree in C++

I'm trying to implement a binary tree in C++ and transverse it in a root-left-right manner. 我正在尝试在C ++中实现一个二叉树,并以root-left-right的方式进行横向处理。 After I add all the nodes I get a crash at this line: 添加所有节点后,我在此行崩溃:

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

My RSD function doesn't print anything. 我的RSD函数不打印任何内容。 Also, I would appreciate any Visual Studio tutorials on how to use the debugger. 另外,我将感谢任何有关如何使用调试器的Visual Studio教程。 Thank you. 谢谢。

#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);
}

The problem is that you pass a copy of a pointer to a read_tree function. 问题是您将指针的副本传递给read_tree函数。 That is, when you call read_tree(r) in the main function, r remains NULL regardless of what happens inside the read_tree function. 也就是说,当您在主函数中调用read_tree(r)时,无论read_tree函数内部发生什么, r保持NULL You can fix it by passing a pointer by reference. 您可以通过按引用传递指针来修复它。 That is, changing read_tree(Nod* r) to read_tree(Nod*& r) should fix it. 也就是说,将read_tree(Nod* r)更改为read_tree(Nod*& r)应该可以解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM