简体   繁体   English

打印不平衡的二叉树

[英]Printing unbalanced binary tree

I'm intentionally creating a wrong and unbalanced binary tree in this code: 我故意在此代码中创建错误且不平衡的二叉树:

void createlist (tree*& node) {
node = new tree;  
  node->num = 1;
  node->left = new tree;
  node->left ->num = 2;
  node->right = new tree;
  node->right->num = 3;
  node->left->left = new tree;
  node->left->left->num = 4;
  node->left->right = new tree;
  node->left->right->num = 5; 
  node->right->left = new tree;
  node->right->left->num = 6;
  node->left->left->left = new tree;
  node->left->left->left->num = 7;
}

Then, when I am trying to print it using an ordinary function for that: 然后,当我尝试使用普通函数对此进行打印时:

void print (tree* node) {
        if (node!= 0) {
            print (node->left);
            cout << node->num << " ";
            print (node->right);
        }
    }

It throws out an error: 它抛出一个错误:

Access violation reading location 0xcdcdcdd5.

at this location: 在此位置:

print (node->left);

I'm just starting with trees and don't quite follow the reason for this error. 我只是从树开始,并不完全了解此错误的原因。 Could you help with that? 你能帮忙吗?

Hard to tell without the source of your tree class, but perhaps making a new tree doesn't initialize the left and right members to null pointers? 很难说没有你的源tree类,但也许让一个new tree不初始化leftright会员空指针? In that case, some of your trees will contain uninitialized pointer data. 在这种情况下,您的某些树将包含未初始化的指针数据。

This is an excellent chance for you to learn how to debug your programs. 这是您学习如何调试程序的绝好机会。 I suggest you run the program in a debugger and see what the values of node and node->left is when the segfault happens. 我建议您在调试器中运行该程序,看看发生段故障时node和node-> left的值是什么。

An access violation is when you are accessing memory that your program is not allowed to access. 访问冲突是指访问程序时不允许访问的内存。

Your problem is not trees your problem is using pointers correctly and not initializing your variables properly. 您的问题不是树,您的问题是正确使用指针并且未正确初始化变量。

I suspect your problem is that the constructor for tree is not properly doing: 我怀疑您的问题是tree的构造函数未正确执行:

left = NULL;
right = NULL;

Remember in C/C++ that the compiler does not set any specific values into variables when they are created, it is up to you to initialize variables. 请记住,在C / C ++中,编译器在创建变量时不会将任何特定值设置为变量,而是由您来初始化变量。

It is custom to use NULL (or nullptr in C++11) to rather than 0 to test/set pointers. 通常使用NULL(或C ++ 11中的nullptr)来测试/设置指针,而不是使用0。

Link to C++ pointers tutorial 链接到C ++指针教程

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

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