145. Binary Tree Postorder Traversal

来源:互联网 发布:nbiot网络架构 编辑:程序博客网 时间:2024/06/07 06:25
/**
 * 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)
{
    vector<int> res;
    if(root == NULL) return res;
    stack<TreeNode *> stackOfT;
    TreeNode *tem = root;
    TreeNode *last = root;
    stackOfT.push(tem);
    while (!stackOfT.empty())
    {
        tem = stackOfT.top();
        if( (tem->left == NULL && tem->right == NULL) || (tem->right == NULL && last == tem->left) || (last == tem->right) )
        {
            res.push_back(tem->val);
            last = tem;
            stackOfT.pop();
        }
        else 
        {
            if(tem->right != NULL) stackOfT.push(tem->right);
            if(tem->left != NULL) stackOfT.push(tem->left);
        }
    }
    return res;
}
};
原创粉丝点击