二叉树的非递归后序遍历,如题目中所言,递归算法就比较简单了,非递归算法中,常见的教科书式的也比较中规中矩,不经意在csdn上看到了一篇二叉树遍历的文章,博主在非递归后续遍历的实现上想法很新颖。再次按其思想实现了下,很简洁。
参考博主链接:http://blog.csdn.net/sgbfblog/article/details/7773103
代码:
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
stack<TreeNode *> s1;
stack<TreeNode *> s2;
vector<int> ivec;
if(root)
s1.push(root);
while(!s1.empty())
{
TreeNode *top = s1.top();
s1.pop();
s2.push(top);
if(top->left)
s1.push(top->left);
if(top->right)
s1.push(top->right);
}
while(!s2.empty())
{
TreeNode *top = s2.top();
ivec.push_back(top->val);
s2.pop();
}
return ivec;
}
};