145. Binary Tree Postorder Traversal - cocoder39/coco39_LC GitHub Wiki
145. Binary Tree Postorder Traversal
reverse the process of preorder traversal, reverse the result at the end
pre: root -> left -> right
our process: root -> right -> left (from pre to this process, we always go to right child instead of left child)
post: left -> right -> root (from our process to post, we reverse the result)
vector<int> res;
stack<TreeNode*> s;
while (root || ! s.empty()) {
if (root) {
res.push_back(root->val);
s.push(root);
root = root->right;
}
else { //! root && ! S.empty()
TreeNode* node = s.top();
s.pop();
root = node->left;
}
}
reverse(res.begin(), res.end());
return res;