标签:
对于二叉树的三种遍历方式,它们的难易程度是不一样的,最简单的是先序遍历,其次是中序遍历,最难的是后序遍历方式。但是最难的后序遍历方式,却可以通过最简单的先序遍历方式的变形实现,然后把遍历的结果逆序一下就搞定了。哈哈,物极必反啊!
先看一个最简单的后序的遍历方法的实现,利用先序遍历方式的变形,然后逆序
vector<int> PostOrder(TreeNode *root)
{
vector<int> result;
stack<const TreeNode*> s;
const TreeNode* cur = root;
if(cur != NULL)
s.push(cur);
while(!s.empty())
{
cur = s.top();
s.pop();
result.push_back(cur->val);
if(cur->left)
s.push(cur->left);
if(cur->right)
s.push(cur->right);
}
reverse(result.begin(), result.end());
return result;
}
其中用到了一个std中的reverse函数,下面对这个函数做一个简单的说明:
这个函数的头文件为:
#include <algorithm> // std::reverse
这个函数对vector逆序的方法就是把vector的begin()和end()作为两个参数传递进去就OK了
http://www.tuicool.com/articles/rIjeEz
标签:
原文地址:http://www.cnblogs.com/stemon/p/4676251.html