树遍历不打印正确的顺序

时间:2015-01-28 22:59:25

标签: c++ tree traversal insertion

我用C ++中的类创建了一个二叉树。我的插入函数是非递归的,如下所示:

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;
    }
}

我使用此功能遍历并使用邮政订单遍历打印树:

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

我在main中插入并打印值,如下所示:

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

运行代码时我应该看到的值如下: 价值:2 价值:4 价值:3 价值:7 价值:6 价值:5

但是,我看到了这个: 价值:3 价值:2 价值:4 价值:6 价值:7 价值:5

有谁可以告诉我为什么以不正确的顺序打印出值?

1 个答案:

答案 0 :(得分:1)

您在preOrderPrintRec()功能中呼叫postOrderPrintRec()。这意味着您只在树的顶层执行后序遍历。请改为拨打postOrderPrintRec(),我认为这样可以解决问题。

相关问题