Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [3,2,1].
Note: 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) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
std::unordered_map<TreeNode *, bool> visited_map;
std::stack<TreeNode *> node_stack;
TreeNode * current = root;
while(current || !node_stack.empty())
{
while(current)
{
node_stack.push(current);
visited_map[current] = false;
current = current->left;
}
TreeNode * top_node = node_stack.top();
if(visited_map[top_node])
{
result.push_back(top_node->val);
node_stack.pop();
}
else
{
visited_map[top_node] = true;
current = top_node->right;
}
}
return result;
}
};