// Recursive
// Iterative
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
std::vector<int> tree;
std::stack<TreeNode*> roots;
TreeNode* prev = nullptr;
while (root || !roots.empty()) {
if (root) {
roots.push(root);
root = root->left;
} else {
auto curr = roots.top();
if (curr->right && prev != curr->right) {
root = curr->right;
} else {
tree.push_back(curr->val);
prev = curr;
roots.pop();
}
}
}
return tree;
}
};
// Morris