您的位置:首页 > 其它

二叉树之遍历(递归和非递归解法)

2016-05-24 23:40 381 查看

一、前序遍历

1、递归遍历:

主函数:

void PreOrder()
{
_PreOrder(_root);
cout<<endl;
}
递归函数:

void _PreOrder(Node* root)
{
if (root == NULL)
return;
cout << root->_data << " ";
_PreOrder(root->_left);
_PreOrder(root->_right);
}

2、非递归遍历

void PreOrder_NonR()
{
if (_root == NULL)
return;

stack<Node*> s;
s.push(_root);
while (!s.empty())
{
Node* top = s.top();
s.pop();
cout << top->_data << " ";
if (top->_right != NULL)
{
s.push(top->_right);
}
if (top->_left != NULL)
{
s.push(top->_left);
}
}
cout << endl;
}

二、中序遍历

1、递归遍历

主函数:

void Inorder()
{
_Inorder(_root);
cout << endl;
}递归函数:
void _Inorder(Node* root)
{
if (root == NULL)
{
return;
}
_Inorder(root->_left);
cout << root->_data <<" ";
_Inorder(root->_right);
}

2、非递归遍历

void InOrder_NonR()
{
if (_root == NULL)
return;
Node* cur = _root;
stack<Node*> s;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->_left;
}
if (!s.empty())
{
Node* top = s.top();
s.pop();
cout << top->_data << " ";
cur = top->_right;
}
}
cout << endl;
}

三、后序遍历

1、递归遍历

主函数

void PosOrder()
{
_PosOrder(_root);
cout << endl;
}

递归函数:
void _PosOrder(Node* root)
{
if (root == NULL)
return;
_PosOrder(root->_left);
_PosOrder(root->_right);
cout << root->_data << " ";
}

2、非递归遍历

void PosOrder_NonR()
{
if (_root == NULL)
return;
Node* prev = NULL;
Node* cur = _root;
stack<Node*> s;
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 << " ";
s.pop();
prev = top;
}
else
{
cur = top->_right;
}

}
cout << endl;
}

四、层序遍历

利用队列先进先出的特性

void LevelOrder()
{
if (_root == NULL)
return;
queue<Node*> q;
q.push(_root);
while (!q.empty())
{
Node* front = q.front();
cout << front->_data << " ";
q.pop();
if (front->_left != NULL)
{
q.push(front->_left);
}
if (front->_right != NULL)
{
q.push(front->_right);
}
}
cout << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树