二叉树的非递归遍历(前序,中序,后序和层序遍历)
Posted 请叫我小小兽
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树的非递归遍历(前序,中序,后序和层序遍历)相关的知识,希望对你有一定的参考价值。
void _PrevOrderNR(Node* root) //非递归前序遍历
{
if (root == NULL)
return;
Node* cur = root;
stack<Node*> s;
while(cur||!s.empty())
{
while (cur)
{
cout << cur->_data << " ";
s.push(cur);
cur = cur->_left;
}
Node* top = s.top();
s.pop();
cur = top->_right;
}
cout << endl;
}
void _InOrderNR(Node* root) //非递归中序遍历
{
Node* cur = root;
stack<Node*> s;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->_left;
}
Node* top = s.top();
cout << top->_data << " ";
s.pop();
cur = top->_right;
}
cout << endl;
}
void _PostOrderNR(Node* root) //非递归后序遍历
{
stack<Node*> s;
Node* cur = root;
Node* prev = NULL;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->_left;
}
Node* top = s.top();
if (top->_right == NULL || top->_right == prev)
{
cout << top->_data << " ";
prev = top;
s.pop();
}
else
{
cur = top->_right;
}
}
cout << endl;
}
void _LevelOrder(Node* root) //层序遍历
{
Node* cur = root;
queue<Node*> q;
if (root)
q.push(root);
while (!q.empty())
{
Node* front = q.front();
q.pop();
cout << front->_data << " ";
if (front->_left)
q.push(front->_left);
if (front->_right)
q.push(front->_right);
}
cout << endl;
}
以上是关于二叉树的非递归遍历(前序,中序,后序和层序遍历)的主要内容,如果未能解决你的问题,请参考以下文章