Having an issue with an exception (Stack overflow) being thrown when using an In Order traversal member function

0

I'm trying to test out my recursive In Order traversal function on a Binary Search Tree but I keep getting an exception thrown (Stack Overflow) when I call that particular function to display nodes on the tree. Am I missing a key part of code?

I've tried looking up how to handle the exception elsewhere but nothing has worked so far. I've also changed the function to a const because I wasn't sure if that's what the compiler (Visual Studio 2017) wanted. I have tested the Pre-Order and Post-Order traversal functions and both work as intended.

In-Order traversal function is a private member function of another class and is called by a separate public function that simply passes the root of the tree to displayInOrder.

void displayInOrder(TreeNode *&root) const {

        if (root == NULL) {

            return;

        }

        else if (root) {

            displayInOrder(root);
            cout << root->value << " ";
            displayInOrder(root->right);
        }
    }

Exception thrown at 0x00C22FE9 in Binary Tree Application.exe: 0xC0000005: Access violation writing location 0x00CA0F60.

c++
exception
binary-search-tree
asked on Stack Overflow Aug 7, 2019 by Christian Dominguez • edited Aug 7, 2019 by CuriouslyRecurringThoughts

1 Answer

2
displayInOrder(root);

should be

displayInOrder(root->left);

The first version is infinitely recursive because you are calling the same function with the exact same parameters. This leads to stack overflow, as you've found.

answered on Stack Overflow Aug 7, 2019 by john • edited Aug 7, 2019 by john

User contributions licensed under CC BY-SA 3.0