二叉树之遍历(递归和非递归解法)
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;
}
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- 一波二叉树遍历问题的C++解答实例分享
- 举例讲解C语言程序中对二叉树数据结构的各种遍历方式
- C++非递归队列实现二叉树的广度优先遍历
- PHP实现的线索二叉树及二叉树遍历方法详解
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#非递归先序遍历二叉树实例
- C++将二叉树转为双向链表及判断两个链表是否相交
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- C++实现查找二叉树中和为某一值的所有路径的示例
- 用C语言判断一个二叉树是否为另一个的子结构
- C++实现二叉树非递归遍历方法实例总结
- C++二叉树结构的建立与基本操作
- 深入遍历二叉树的各种操作详解(非递归遍历)
- Python实现二叉树结构与进行二叉树遍历的方法详解