问题描述
给出一棵二叉树,返回其节点值的后序遍历。
样例
给出一棵二叉树 {1,#,2,3},
1
\
2
/
3
返回 [3,2,1].
挑战
你能使用非递归实现么?
求解
class Solution2
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> res;
stack<pair<TreeNode *, bool>> s;
s.emplace(root, false);
while (!s.empty())
{
bool visited;
tie(root, visited) = s.top();
s.pop();
if (root == nullptr)
{
continue;
}
if (visited)
{
res.emplace_back(root->val);
}
else
{
s.emplace(root, true);
s.emplace(root->right, false);
s.emplace(root->left, false);
}
}
return res;
}
};