树遍历未打印正确的顺序

Tree Traversal not printing correct order

本文关键字:顺序 打印 遍历      更新时间:2023-10-16

我在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

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

你在postOrderPrintRec()函数中调用preOrderPrintRec()。 这意味着您只在树的顶层执行后序遍历。 改为打电话给postOrderPrintRec(),我认为这将解决它。