为什么写这篇帖子
这篇帖子的代码是在上大学修数据结构的时候写的,写完就上传提供下载了,那会比较贪心,设置的下载积分比较高。工作后慢慢习惯分享,偶然看到当时上传的简单几行代码还要积分。干脆直接把代码拿过来写成帖子也省去了路过同仁下载的麻烦。
这篇帖子都写了什么
如题,这篇帖子给出了二叉树三种遍历算法的非递归实现。目前,我只给出了算法的具体代码实现,具体的算法描述并没有提及(貌似也没有必要说,算法很简单)。
顺便提一下本文中的算法使用C++描述。
具体聊聊代码
二叉树数据结构
//定义二叉树结构
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
遍历算法实现
非递归先序遍历
//非递归先序遍历
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
st.push(root);
while (!st.empty() && root != nullptr)
{
auto temp = st.top();
st.pop();
if (temp == nullptr)
{
continue;
}
else
{
res.push_back(temp->val);
st.push(temp->right);
st.push(temp->left);
}
}
return res;
}
非递归中序遍历
//非递归中序遍历
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if (root == nullptr)
{
return res;
}
stack<TreeNode*> s;
while (root != nullptr || !s.empty())
{
while (root)
{
s.push(root);
root = root->left;
}
if (!s.empty())
{
root = s.top();
res.push_back(root->val);
s.pop();
root = root->right;
}
}
return res;
}
非递归后序遍历
//非递归后序遍历
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if (root == nullptr)
{
return res;
}
stack<TreeNode*> s;
vector<TreeNode*> v;
s.push(root);
while (!s.empty())
{
while (s.top()->left&&find(v.begin(), v.end(), s.top()->left) == v.end())
{
s.push(s.top()->left);
}
root = s.top();
if (root->right&&find(v.begin(), v.end(), s.top()->right) == v.end())//认为没有左节点
{
s.push(root->right);
}
else//认为没有右节点
{
res.push_back(root->val);
v.push_back(root);
s.pop();
}
}
return res;
}
结束语
以上就是二叉树三种遍历算法的递归与非递归实现的具体代码,如有不明白的地方欢迎留言交流,若帖子中有错误的地方同样欢迎留言批评指正,在此谢过路过的各位大神。