Search code examples
c++treetraversalinsertion

Tree Traversal not printing correct order


I have created a binary tree out of classes in C++. My insert function is non-recursive and looks like this:

bool Tree1::inOrderInsert(int x)
{
    TreeNode *parent = NULL;
    TreeNode *temp = root;
    TreeNode *newNode = new TreeNode(x);

    if (root == NULL)
    {
        root = newNode;
        //cout << "Root empty!" << endl;
        return true;
    }

    while (temp != NULL)
    {
        if (x <= temp->value)
        {
            parent = temp;
            temp = temp->left;
        }
        else
        {
            parent = temp;
            temp = temp->right;
        }
    }

    if (x <= parent->value)
    {
        parent->left = newNode;
        return true;
    }
    else
    {
        parent->right = newNode;
        return true;
    }
}

I traverse and print the tree using post order traversal with this function:

void Tree1::postOrderPrintRec(TreeNode *node)
{
    if (node != NULL)
    {
        preOrderPrintRec(node->left);
        preOrderPrintRec(node->right);
        cout << "Value: " << node->value << endl;
    }
}

I insert and print values in main like this:

tree1.inOrderInsert(5);
tree1.inOrderInsert(3);
tree1.inOrderInsert(2);
tree1.inOrderInsert(4);
tree1.inOrderInsert(6);
tree1.inOrderInsert(7);
tree1.postOrderPrintRec(tree1.getRoot()); 

The values I should be seeing when I run the code are as follows: value: 2 value: 4 value: 3 value: 7 value: 6 value: 5

However, I am seeing this: value: 3 value: 2 value: 4 value: 6 value: 7 value: 5

Can anyone tell me why it is printing out values in the incorrect order?


Solution

  • You're calling preOrderPrintRec() inside your postOrderPrintRec() function. This means you're only doing a post-order traversal at the top level of the tree. Call postOrderPrintRec() instead, and I think that will fix it.