leetcode 145 二叉树的后序遍历

地址:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
大意:给定一个二叉树,返回它的 后序 遍历。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
struct Comm{
    string s;
    TreeNode *node;
    Comm(string s,TreeNode *node): s(s),node(node) {}
};

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        stack<Comm> stack;
        vector<int> res;
        if(root == NULL)
            return res;
        stack.push(Comm("go",root));
        while(stack.size() != 0){
            Comm com = stack.top();
            stack.pop();

            if(com.s == "print"){
                res.push_back(com.node->val);
            }else{
                stack.push(Comm("print",com.node));
                if(com.node->right)
                    stack.push(Comm("go",com.node->right));
                if(com.node->left)
                    stack.push(Comm("go",com.node->left));
            }
        }
        return res;
    }
};
posted @ 2020-04-12 18:41  一只小白的进修路  阅读(177)  评论(0)    收藏  举报