leetcode #145 in cpp

Solution:

The post-order is the reverse of the root->right->left order. The root->right->left order is similar to pre-order traversal. Thus we first do a pseudo-pre-order traversal, by collecting root first, then right node, then left node. As we collect all nodes we reverse the collection. 

Code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> stk1; 
        stack<TreeNode*> stk2; 
        if(root) stk1.push(root);
        TreeNode*cur; 
        while(!stk1.empty()){
            cur = stk1.top();
            stk1.pop();
            stk2.push(cur);
            if(cur->left) stk1.push(cur->left);
            if(cur->right) stk1.push(cur->right);
            
        }
        vector<int> res;
        while(!stk2.empty()){
            res.push_back(stk2.top()->val);
            stk2.pop();
        }
        return res; 
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值