后序遍历

类似前序遍历,不过入栈时是先left再right,得到根右左,再对结果反转得到左右根

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        if(root == nullptr)
            return res;
        
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty())
        {
            TreeNode* cur = st.top();
            st.pop();
            if(cur!=nullptr){
                res.push_back(cur->val);
                st.push(cur->left);
                st.push(cur->right);
            }
        }
        
        reverse(res.begin(),res.end());
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_22080999/article/details/80410781