rec c++


  • 0

    class Solution {
    public:
    void lrm(TreeNode* root, vector<int>& res){
    if(root==NULL)return;
    lrm(root->left,res);
    lrm(root->right,res);
    res.push_back(root->val);
    }
    vector<int> postorderTraversal(TreeNode* root) {
    vector<int> res;
    lrm(root,res);
    return res;
    }
    };


  • 0

    //UNRECUR

    class Solution {
    public:

    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        st.push(root);
        
        vector<int> res;
        while(!st.empty()){
            TreeNode* tmp=st.top();
            st.pop();
            if(tmp==NULL){continue;}
            if(tmp->left==NULL&&tmp->right==NULL){
                
                res.push_back(tmp->val);
                continue;
            }
            auto left=tmp->left;
            auto right=tmp->right;
            tmp->left=NULL;tmp->right=NULL;
            st.push(tmp);
            if(right!=NULL){
                st.push(right);
            }
            if(left!=NULL){
                st.push(left);
            }
            
        }
        return res;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.