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;
}
};