145. 二叉树的后序遍历

发布时间 2023-05-21 15:26:03作者: 穿过雾的阴霾
/**
 * 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:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> st;
        while(root||st.size())
        {
            while(root)
            {
                res.push_back(root->val);
                st.push(root);
                root=root->right;
            }
            root=st.top();
            st.pop();
            root=root->left;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};