Share my easy understanding c++ solution 2ms


  • 8
    K
    //use a stack
    //stack pop order:root,right,left
    //reverse the result
    class Solution {
    public:
    	vector<int> postorderTraversal(TreeNode* root) {
    		vector<int> res;
    		stack<TreeNode*> tree;
    		TreeNode* tmp;
    		if(!root)
    			return res;
    		tree.push(root);
    		while(!tree.empty()){
    			tmp=tree.top();
    			tree.pop();
    			res.push_back(tmp->val);
    			if(tmp->left)
    				tree.push(tmp->left);
    			if(tmp->right)
    				tree.push(tmp->right);
    		}
    		reverse(res.begin(),res.end());
    		return res;
    	}	
    };

  • 0
    O

    hey the reverse is kind of cheating but I like you idea


  • 0
    K

    ha-ha,thank you


  • -1
    L

    I used the same idea to solve the problem...


Log in to reply
 

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