二叉树的非递归遍历(前序,中序,后序和层序遍历)
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;
}