【问题标题】:Difference Between Two Iterative Solutions for PreOrder Traversal of a Binary Tree二叉树前序遍历的两种迭代解的区别
【发布时间】:2018-12-07 19:19:27
【问题描述】:

截至目前,我正在尝试通过在 Java 中使用 Stack 对象来直观地理解递归。在 GeeksForGeeks 上,他们在二叉树上的遍历方法上有练习问题。目前我在 PreOrder 上,虽然我已经找到了递归解决方案,但事实证明,提出迭代解决方案非常麻烦。当我提出问题的实际答案时,我发现我的代码实际上与解决方案代码相同。我已经来回走了一段时间,试图弄清楚为什么我的 PreOrder 遍历的迭代解决方案与实际解决方案相比是不正确的,但我认为也许我需要第三组更有经验的眼睛来告诉我为什么我会错误的。

这是问题的 url 和在线编译器:https://practice.geeksforgeeks.org/problems/preorder-traversal/1

这是我的代码:

void preorder(Node root)
{
   // Your code goes here
   if(root == null) return;
   Stack<Node> stack = new Stack<Node>();

   stack.push(root);
   while(!stack.isEmpty()) {
       Node cur = stack.pop();
       System.out.print(cur.data + " ");

       if(cur.left != null) {
           stack.push(cur.left);
       }
       if(cur.right != null) {
           stack.push(cur.right);
       }
   }
}

解决方法代码如下:

void preorder(Node root) { 

    // Base Case 
    if (root == null) { 
        return; 
    } 

    // Create an empty stack and push root to it 
    Stack<Node> nodeStack = new Stack<Node>(); 
    nodeStack.push(root); 

    /* Pop all items one by one. Do following for every popped item 
     a) print it 
     b) push its right child 
     c) push its left child 
     Note that right child is pushed first so that left is processed first 
*/
    while (nodeStack.empty() == false) { 

        // Pop the top item from stack and print it 
        Node mynode = nodeStack.peek(); 
        System.out.print(mynode.data + " "); 
        nodeStack.pop(); 

        // Push right and left children of the popped node to stack 
        if (mynode.right != null) { 
            nodeStack.push(mynode.right); 
        } 
        if (mynode.left != null) { 
            nodeStack.push(mynode.left); 
        } 
    } 
} 

【问题讨论】:

  • 您首先推送左侧节点,这意味着您将在左侧之前弹出(并因此处理)右侧节点。他们在解决方案的评论中对此进行了解释。

标签: java iteration binary-tree preorder


【解决方案1】:

二叉树的前序遍历是Visit,Left and Right

您的代码与解决方案的代码不同。

您需要先将right 子项推入堆栈,然后将left 子项将left 子项带到堆栈顶部,然后访问该子项。因此,如下所示修改您的代码-

void preorder(Node root)
{
   // Your code goes here
   if(root == null) return;
   Stack<Node> stack = new Stack<Node>();

   stack.push(root);
   while(!stack.isEmpty()) {
       Node cur = stack.pop();
       System.out.print(cur.data + " ");

       if(cur.right != null) {
           stack.push(cur.right);
       }

       if(cur.left != null) {
           stack.push(cur.left);
       }

   }
}

【讨论】:

  • 哈哈!非常感谢。我盯着代码看了这么久,我一定是刷了很多次订单。感谢您澄清堆栈的外观。我现在真的明白了。
  • @P_Locked 很高兴为您提供帮助 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多