简体   繁体   中英

Traversing and Printing a Binary Tree Level by Level

I am trying to traverse a binary tree built with the input data from keyboard. Data is inserted to the binary tree successfully. I have a switch statement, where 'case 4' should traverse (and print) the binary tree level by level. However I got EXC_BAD_ACCESS error. I would be more than happy if someone help me out with this one.

(RootPtr is the top -Level 0- node of the binary tree defined globally; TreeDepth() is the function calculating "Depth" of the tree where Depth defined globally and root node has depth of 0; and GetNode is basically an initializer function (using malloc) for type TreePtr pointers.)

Thank you all in advance.

Here is the relevant code:

This is the struct definition;

    typedef struct treeItem
{
    int data;
    struct treeItem *left;
    struct treeItem *right;

}Tree , *TreePtr;

This is the switch case where I call Level by Level traversing function(s);

case 4:
                TreePtr temp;
                GetNode(&temp);

                temp = RootPtr;

                printLevelOrder(temp);
                printf("\n\n");

                break;

These are the functions used for traversing the tree level by level;

void printGivenLevel(TreePtr TemPtr, int level)
{
    if (items == 0)
        return;
    else
    {    if(level == 0 )
        {
            printf(" %d", (*TemPtr).data); //the line I got ERROR
        }
        else
        {
            printGivenLevel((*TemPtr).left, (level-1));
            printGivenLevel((*TemPtr).right, (level-1));
        }
    }
}

void printLevelOrder(TreePtr TemPtr)
{
    TreeDepth();
    if (items == 0)
        printf("\nTree is empty.\n");
    else
    {
        printf("Traverse level by level:");

        for (int i=0; i<=Depth; i++)
        {
            printGivenLevel(TemPtr, i);
        }
    }
}

It's an off by one error. In your for loop:

for (int i=0; i<=Depth; i++)

You're traversing this loop Depth + 1 times. This means you're trying to access one more level than there actually is. In particular, in the final call of printGivenLevel , in the point in the recursion where level == 1 , you're already at the bottom of the tree. You're now recursing one more time, but the pointers you pass into the next recursion level are garbage pointers (they aren't guaranteed to point to memory you're allowed to access, or even exists). So when you try to dereference them, you get an error.

One more thing: this implementation is pretty inefficient, since you're traversing the tree many times. It's better to do a breadth-first search, like kiss-o-matic mentioned. This way, you'll only traverse the tree once, which is much faster (although it does use more memory).

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