Problem:
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?
Analysis:
Solutions:
C++:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> node_list;
if(root == NULL)
return node_list;
TreeNode *p_cur = root;
TreeNode *p_visited = NULL;
stack<TreeNode *> node_stack;
while(p_cur || !node_stack.empty()) {
if(p_cur) {
node_stack.push(p_cur);
p_cur = p_cur->left;
} else {
p_cur = node_stack.top();
if(p_cur->right == NULL || p_cur->right == p_visited) {
node_list.push_back(p_cur->val);
p_visited = p_cur;
node_stack.pop();
p_cur = NULL;
} else
p_cur = p_cur->right;
}
}
return node_list;
}
Java
:
Python: