通过栈实现二叉树的后序遍历
void postorderTraversal(TreeNode* root)
{
if (root == nullptr)
{
return;
}
stack<TreeNode*> stk;
TreeNode* cur = root;
TreeNode* lastVisited = nullptr;
while (cur != nullptr || !stk.empty())
{
if (cur != nullptr)
{
stk.push(cur);
cur = cur->left;
}
else
{
cur = stk.top();
if (cur->right != nullptr && lastVisited != cur->right)
{
cur = cur->right;
}
else
{
cout << cur->val << " ";
lastVisited = cur;
stk.pop();
cur = nullptr;
}
}
}
}