Search code examples
c++iterationbinary-treeinordernon-recursive

Cannot traverse a binary tree with non-recursive inorder method


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 3' should traverse (and print) the binary tree with non-recursive Inorder traversal algorithm. However when 'case 3' is called, it gives an EXC_BAD_ACCESS error, which never makes any sense to me. 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; and GetNodeS is basically an initializer function (using malloc) for type StackPtr pointers.)

Thank you all in advance.

Here is the relevant code:

These are struct definitions,

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

}Tree , *TreePtr;

typedef struct stackItem
{
    TreePtr t;
    struct stackItem *next;

}Stack , *StackPtr;

These are Push and Pop functions,

void PushS (TreePtr TreePointer)
{
    StackPtr TemPtr;
    GetNodeS(&TemPtr);

    (*TemPtr).t = TreePointer;
    (*TemPtr).next = S;
    S = TemPtr;
}

void PopS(TreePtr TreePointer)
{
    StackPtr TemPtr;
    GetNodeS(&TemPtr);

    if (S != NULL)
    {
        TreePointer = (*S).t;
        TemPtr = S;
        S = (*S).next;

        FreeNodeS(TemPtr);
    }    
    else
        printf("\nEmpty stack!");

}

This is the traversing function,

void iterative (TreePtr TemPtr)
{
    DONE = 0;
    TemPtr = RootPtr;
    S = NULL;

    if(items==0)
    {
        printf("\nTree is empty.\n\n");
        DONE = 1;
    }
    else
    {
        printf("\nIterative nonrecursive inorder traversal:");

        while (DONE == 0)
        {
            if(TemPtr != NULL)
            {
                PushS(TemPtr);
                TemPtr = (*TemPtr).left;
            }
            else
                if(S != NULL)
                {
                    PopS(TemPtr);
                    printf(" %d", (*TemPtr).data); //the line I get the ERROR
                    TemPtr = (*TemPtr).right;
                }
                else
                {
                    DONE = 1;
                }
        }
    }
}

And this is the switch case where I try to call iterative traversing function,

     case 3:
            TreePtr TemPtr;
            GetNode(&TemPtr);

            iterative(TemPtr);

            break;

Solution

  • You are dereferencing a null pointer on the line where you get the error. That is the cause of the EXC_BAD_ACCESS error.

    if(TemPtr != NULL)
    {
        ...
    }
    else // TemPtr must be NULL here
    

    PopS(TemPtr); does not change TempPtr as it is passed by value.

    Then here:

    printf(" %d", (*TemPtr).data);
    

    *TemPtr is a null pointer dereference.