// 严格按照后序遍历的定义
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> v;
stack<TreeNode*> s_stack;
TreeNode *node = root;
TreeNode *lastVisitNode = NULL;
while (!s_stack.empty() || node != NULL){
if (node != NULL){
// keep going the left
s_stack.push(node);
node = node->left;
}
else{
TreeNode *n = s_stack.top();
// left way is finsised, keep going to the right way
if (n->right != NULL && lastVisitNode != n->right){
node = n->right;
}
else{
// both left and right has been accessed.
s_stack.pop();
v.push_back(n->val);
//更新上次被访问的节点
lastVisitNode = n;
}
}
}
return v;
}
};