二叉树遍历实现
本文以二叉树为例,介绍二叉树的三种遍历方式:1.先序遍历;2.中序遍历;3.后序遍历。
关于二叉树的遍历方式主要有两种思路:递归和非递归,对于算法题的思路,初学者一般能不用递归就不用递归,但二叉树遍历方式递归方式思路较为简单,代码长度和复杂性远小于非递归,故在此介绍二叉树遍历的递归方式。
1.二叉树的创建
#include <iostream>
using namespace std;
//创建二叉树类
class BinTree{
public:
BinTree();
BinTree(int a);
int val;
BinTree* childLeft;
BinTree* childRight;
void CreateTree();//创建树
};
BinTree::BinTree(){
};
BinTree::BinTree(int a){
val = a;
}
//创建二叉树
// 1
// / \
// 2 3
// /\ /\
// 4 5 6 7
void BinTree::CreateTree(){
val = 1;
childLeft = new BinTree(2);
this->childRight = new BinTree(3);
// 左子树
childLeft->childLeft = new BinTree(4);
childLeft->childLeft->childLeft = NULL;
childLeft->childLeft->childRight = NULL;
childLeft->childRight = new BinTree(5);
childLeft->childRight->childLeft = NULL;
childLeft->childRight->childRight = NULL;
//右子树
childRight->childLeft = new BinTree(6);
childRight->childLeft->childLeft = NULL;
childRight->childLeft->childRight = NULL;
childRight->childRight = new BinTree(7);
childRight->childRight->childLeft = NULL;
childRight->childRight->childRight = NULL;
}
遍历方法类:
class TreeTraversal{
public:
TreeTraversal();
int frontTraversing(BinTree* t);//先序遍历
int midTraversing(BinTree* t);//中序遍历
int afterTraversing(BinTree* t);//后序遍历
};
TreeTraversal::TreeTraversal(){};
2.先序遍历
若二叉树为空则空操作;否则
1.访问根节点
2.先序遍历左子树
3.先序遍历右子树
方法实现:
//先序遍历:1.根节点,2.左子树,3.右子树,递归做法
int TreeTraversal::frontTraversing(BinTree* t){
if(t != NULL){
printtreeNode(t);
frontTraversing(t->childLeft);
frontTraversing(t->childRight);
}
return 0;
}
//打印树节点值
void printtreeNode(BinTree* t1){
cout<<t1->val<<" ";
}
main函数:
int main(){
BinTree* myTree = new BinTree();
myTree->CreateTree();
TreeTraversal* s = new TreeTraversal();
cout<<"先序遍历"<<endl;
s->frontTraversing(myTree);
return 0;
}
3.中序遍历
若二叉树为空则空操作;否则
1.中序遍历左子树
2.访问根节点
3.中序遍历右子树
方法实现:
//中序遍历:1.左子树;2.根节点;3.右子树
int TreeTraversal::midTraversing(BinTree* t){
if(t != NULL){
midTraversing(t->childLeft);
printtreeNode(t);
midTraversing(t->childRight);
}
return 1;
}
//打印树节点值
void printtreeNode(BinTree* t1){
cout<<t1->val<<" ";
}
main函数:
int main(){
BinTree* myTree = new BinTree();
myTree->CreateTree();
TreeTraversal* s = new TreeTraversal();
cout<<"中序遍历"<<endl;
s->midTraversing(myTree);
return 0;
}
4.后序遍历
若二叉树为空则空操作;否则
1.后序遍历左子树
2.后序遍历右子树
3.访问根节点
方法实现:
//后序遍历:1.左子树;2.右子树;3.根节点
int TreeTraversal::afterTraversing(BinTree* t){
if(t != NULL){
afterTraversing(t->childLeft);
afterTraversing(t->childRight);
printtreeNode(t);
}
return 2;
}
//打印树节点值
void printtreeNode(BinTree* t1){
cout<<t1->val<<" ";
}
main函数:
int main(){
BinTree* myTree = new BinTree();
myTree->CreateTree();
TreeTraversal* s = new TreeTraversal();
cout<<"后序遍历"<<endl;
s->afterTraversing(myTree);
return 0;
}
至此,二叉树遍历介绍完毕,此为基础内容,需要牢记!