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 a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct PTNode {
TreeNode *node;
bool bFirst;
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode *> s;
while (!s.empty() || root != NULL) {
while (root != NULL) {
s.push(root);
result.insert(result.begin(), root->val);
root = root->right;
}
root = s.top();
s.pop();
root = root->left;
}
return result;
}
};