/*
 * @lc app=leetcode.cn id=145 lang=cpp
 *
 * [145] 二叉树的后序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    /*
    迭代版本:
    1、依次访问右子树,将右子树的各个节点采用头插法存储在数组中
    2、当某个节点右子树为空时,该节点出栈,将此节点的左子树压入栈中,倘如左子树为空,访问当前节点的上一节点,如此循环即可
    */

    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==nullptr) return res;
        stack<TreeNode*> record;

        while(!record.empty()|| root!=nullptr){
            if(root){
                record.push(root);
                res.insert(res.begin(),root->val);
                root=root->right;
            }else{
                TreeNode* tmp=record.top();
                record.pop();
                root=tmp->left;
            }
        }           
        return res;
    }
};
// @lc code=end