LeetCode 145. 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) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        if(root == NULL) return ans;
        stack<TreeNode*> s;
        s.push(root);
        while(!s.empty()){
            TreeNode* cur = s.top();
            s.pop();
            ans.push_back(cur -> val);
            if(cur -> left != NULL) s.push(cur -> left);
            if(cur -> right != NULL) s.push(cur -> right);
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

  

posted @ 2020-03-20 17:13  Somnuspoppy  阅读(103)  评论(0编辑  收藏  举报