【发布时间】: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