【发布时间】:2018-05-15 21:09:26
【问题描述】:
我正在尝试使用堆栈来理解 DFS 树遍历。我发现将递归解决方案转换为迭代解决方案以进行前序遍历非常直观。但是,我发现使用此链接很难理解后序遍历。 https://www.geeksforgeeks.org/iterative-postorder-traversal-using-stack/。有没有一种直观和简单的思考方式? 预购代码:
void iterativePreorder(node *root)
{
// Base Case
if (root == NULL)
return;
// Create an empty stack and push root to it
stack<node *> nodeStack;
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
struct node *node = nodeStack.top();
printf ("%d ", node->data);
nodeStack.pop();
// Push right and left children of the popped node to stack
if (node->right)
nodeStack.push(node->right);
if (node->left)
nodeStack.push(node->left);
}
}
【问题讨论】:
-
预购和后购没有太大区别。如果您显示预购遍历的代码可能会有所帮助。然后有人可以建议如何调整该代码以适应 postorder。
-
@user3386109 已编辑
-
@user3386109:回复:“预购和后购之间没有太大区别”:我不同意。您可能正在考虑递归实现(它们几乎是相同的),但是使用迭代堆栈实现,预排序可以比后排序更简单地实现。
标签: c++ algorithm binary-tree postorder