【问题标题】:Tree Traversal not printing correct order树遍历没有打印正确的顺序
【发布时间】:2015-03-28 01:11:03
【问题描述】:

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

谁能告诉我为什么它以错误的顺序打印出值?

【问题讨论】:

  • 添加有问题的函数 preOrderPrintRec()。

标签: c++ tree traversal insertion


【解决方案1】:

您在 postOrderPrintRec() 函数中调用 preOrderPrintRec()。这意味着您只在树的顶层进行后序遍历。请致电postOrderPrintRec(),我认为这会解决问题。

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2014-05-07
    • 1970-01-01
    相关资源
    最近更新 更多