二叉树遍历的两个迭代解之间的区别

时间:2018-12-07 19:19:27

标签: java iteration binary-tree preorder

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

以下是问题所在的网址和在线编译器: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); 
        } 
    } 
} 

1 个答案:

答案 0 :(得分:0)

二叉树的遍历遍历为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);
       }

   }
}