简体   繁体   中英

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? 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.

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:

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.

It is custom to use NULL (or nullptr in C++11) to rather than 0 to test/set pointers.

Link to C++ pointers tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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