binary-tree-postorder-traversal leetcode C++

Given a binary tree, return the postorder traversal of its nodes' values.

For example: Given binary tree{1,#,2,3},

  • 1
  • \
  • 2
    
  • /
  • 3

return[3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

 

C++

/**
 * Definition for binary tree
 * 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){
        if (!root) return {};
        vector<int> res;
        stack<TreeNode*> s{{root}};
        while(!s.empty()){
            TreeNode *t = s.top(); s.pop();
            res.insert(res.begin(),t->val);
            if (t->left) s.push(t->left);
            if (t->right) s.push(t->right);
        }
        return res;
    }
};

 

posted @ 2018-09-21 11:34  vercont  阅读(116)  评论(0编辑  收藏  举报