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].
Stack Problem, One example will make this question easy to tackle.
In this example, the post-order sequence is: 4, 5, 2, 6, 3, 1.
The process will be.... We first push 1 onto stack, Get the top element, pop it off, then push the left and right child.....
vector<int> postorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> res;
stack<TreeNode*> nodes;
nodes.push(root);
while(!nodes.empty()) {
TreeNode* tmp = nodes.top();
nodes.pop();
res.push_back(tmp->val);
if(tmp->left) nodes.push(tmp->left);
if(tmp->right) nodes.push(tmp->right);
}
reverse(res.begin(), res.end());
return res;
}
Another way of asking this question is to implement a post-order iterator which has getNext() method, and hasNext() method.
1
/ \
4 2
/ \
3 6 The post order is: 4 3 6 2 1 (left substree, root, right substree)
class postOrderIterator {
stack<TreeNode*> nodes;
public:
void findNextLeave(TreeNode* root) {
TreeNode* curr = root;
while(curr) {
nodes.push_back(curr);
if(curr->left) curr = curr->left;
else if(curr->right) curr = curr->right;
}
}
bool hasNext() {
return !nodes.empty();
}
int getNext() {
TreeNode* res = nodes.top();
nodes.pop();
while(!nodes.empty()) {
TreeNode* tmp = nodes.top();
if(res == tmp->left) { // left is done, traversal the right.
findNextLeave(tmp->right);
}
}
return res->val;
}
}

本文介绍了一种使用栈实现二叉树后序遍历的方法,并提供了两种不同的实现思路:一种是直接利用栈进行遍历后反转结果;另一种是通过迭代的方式找到下一个叶子节点。
313

被折叠的 条评论
为什么被折叠?



