我正在尝试使用堆栈了解 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);
}
}