【问题标题】:Preorder Traversal (Binary Tree) - Iterative Method前序遍历(二叉树) - 迭代法
【发布时间】:2021-03-20 06:50:18
【问题描述】:

我正在实现二叉树的前序遍历(无递归)。以下代码运行到无限循环。我无法理解发生了什么

void Tree::n_preorder()
{
    Node* temp;        
    stack s;
    cout<<"\nPreorder: ";
    while(1)
    {
        s.push(root);
        while(1)
        {
            temp = s.pop();
            cout<<temp->data;
            if(temp->right)
            {
                s.push(temp->right);        //Push right child
            }
            if(s.isEmpty())
            {
                break;
            }
            if(temp->left)
            {
                s.push(temp->left);         //Push left child
            }
        }
    }
}

栈的isEmpty()函数

int isEmpty()
{
  return top==-1;
}

【问题讨论】:

  • 删除第一个 while 循环。

标签: c++ data-structures tree


【解决方案1】:

外部循环永远不会退出:它的while 条件始终为真,并且它没有break。您拥有的唯一break 将跳出内循环,但不会跳出外循环。

您不需要嵌套循环来执行此操作。当你只有一个循环时,如果不将左子元素放在堆栈上,就没有意义中断它,所以删除那个条件中断,而是让!s.isEmpty()成为你循环的条件:

void Tree::n_preorder()
{
    Node* node;        
    stack nodeStack;
    cout << "\nPreorder:";
    nodeStack.push(root);
    while (!nodeStack.isEmpty())
    {
        node = nodeStack.pop();
        cout << " " << node->data;
        // As a stack is LIFO (last-in-first-out), we add the node's children 
        // on the stack in reversed order, so they get output in the correct order.
        if (node->right)
        {
            nodeStack.push(node->right);
        }
        if (node->left)
        {
            nodeStack.push(node->left);
        }
    }
}

其他一些评论:

  • 我觉得像 "push left child" 这样的 cmets 没有什么用处...因为这只是重复 - 几乎是逐字逐句 - 在相应的代码行中已经可以看到.应该对更高级别的抽象进行评论,并就“为什么?”给出一些解释。我在上面的代码中添加了这样的注释来说明这一点。

  • 使用更具描述性的变量名称。 temps 并没有提供太多。

  • 您需要输出一个空格来分隔不同的数据输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多