C++ code with a stack


  • 0
    N
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            stack<TreeNode*> Tree;
            vector<int> postordervals;
            if(root==NULL){
                return postordervals;
            }
            Tree.push(root);
            while(!Tree.empty()){
                TreeNode* This = Tree.top();
                if(This->left){
                    Tree.push(This->left);
                }
                else if(This->right){
                        Tree.push(This->right);
                    }
                else{
                        TreeNode* TopNode2 = Tree.top();
                        postordervals.push_back(TopNode2->val);
                        Tree.pop();
                        while(!Tree.empty()){
                            TreeNode* TopNode1 = Tree.top();
                            if(TopNode1->left==TopNode2&&TopNode1->right){
                                Tree.push(TopNode1->right);
                                break;
                            }
                            else{
                                TopNode2 = TopNode1;
                                postordervals.push_back(TopNode2->val);
                                Tree.pop();
                            }
                        }
                    }
            }
            return postordervals;
        }
    };

Log in to reply
 

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