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;
}
};
二叉树后序遍历迭代法

本文介绍了一种不使用递归的方法来完成二叉树节点后序遍历的问题,通过栈结构实现了对二叉树节点的迭代访问,并给出了具体的C++实现代码。
302

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



