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?
/**
* 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) {
vector<int> result;
stack<pair<TreeNode*, int>> noderecords;
stack<int> nodeStatus;
if(root != NULL){
noderecords.push(make_pair(root, 0));
}
while(!noderecords.empty()){
TreeNode* n = noderecords.top().first;
int status = noderecords.top().second;
noderecords.pop();
if(status == 0){
noderecords.push(make_pair(n, 1));
if(n->right != NULL){
noderecords.push(make_pair(n->right, 0));
}
if(n->left != NULL){
noderecords.push(make_pair(n->left, 0));
}
}
else{
result.push_back(n->val);
}
}
return result;
}
};