二叉树的递归遍历
遍历是对树的一种最基本的运算,所谓遍历二叉树,就是按一定的规则和顺序走遍二叉树的所有结点,使每一个结点都被访问一次,而且只被访问一次。由于二叉树是非线性结构,因此,树的遍历实质上是将二叉树的各个结点转换成为一个线性序列来表示。
/**********************************************************
*声明:当前节点CurrentNode,根节点root,左节点Lchild,右节点Rchild
*******************************************************/
struct BitTreeNode{
int value;
BitTreeNode* Lchild;
BitTreeNode* Rchild;
BitTreeNode(int x) : val(x), Lchild(NULL), Rchild(NULL) {}
};
先序遍历
a: if CurrentNode==NULL then return;
else visit(CurrentNode);
b: PreOrderSearch CurrentNode->Lchild ;
c: PreOrderSearch CurrentNode->Rchild ;
void BitTreeSearch_preorder(BitTreeNode* root){
if(root==NULL) return; //递归收敛条件
else visit(root); //访问节点
BitTreeSearch_preorder(root->Lchild);
BitTreeSearch_preorder(root->Rchild);
}
中序遍历
a: if CurrentNode==NULL then return;
else BitTreeSearch_inorder(CurrentNode->Lchild) ;
b: visit(CurrentNode) ;
c: BitTreeSearch_inorder(CurrentNode->Rchild) ;
void BitTreeSearch_inorder(BitTreeNode* root){
if(root==NULL) return;
else BitTreeSearch_inorder(root->Lchild);
visit(root);
BitTreeSearch_inorder(root->Rchild);
}
后序遍历
a: if CurrentNode==NULL then return;
else BitTreeSearch_postorder(CurrentNode->Lchild) ;
b: BitTreeSearch_postorder(CurrentNode->Rchild) ;
c: visit(root);
void BitTreeSearch_postorder(BitTreeNode* root){
if(root==NULL) return;
else BitTreeSearch_postorder(root->Lchild);
BitTreeSearch_postorder(root->Rchild);
visit(root);
}
二叉树的非递归遍历
二叉树是一种很基础常用的数据结构,访问树中的元素需要通常是遍历,先序,中序,和后序。通常来说递归算法要比非递归算法易于理解,在数据量小的情况下,由于编译器对经常调用的函数有优化,实际上并不比非递归算法慢很多。然而在数据量大的情况下或者某些特别场合,非递归算法要远优于递归算法。好啦,来复习一下二叉树的非递归实现吧。
结构体与变量声明
struct treenode{
int value;
treenode* lchild;
treenode* rchild;
treenode(int x):value(x),lchild(NULL),rchild(NULL){}
};
treenode* nodes[30];//存放节点,用来模拟栈
int flag[30]={0};//在后序遍历中使用
int current=0;//算是栈顶指针,指向最上面的节点(也就是这个节点在数组中的位置)
//treenode* CurrentNode;//当前操作的节点
nodes[0]->value=0;//存放树的深度,我没有使用
nodes[0]->lchild=NULL;
nodes[0]->rchild=NULL;
先序遍历
void BitTreeSearch_preorder(treenode* root){
do{
while(root){
visit(root);
current++;
nodes[current]=root;
root=root->lchild;
}
if(current){
root=nodes[current];
current--;
root=root->rchild;
}
}while(current);
}
中序遍历
void BitTreeSearch_inorder(treenode* root){
do{
while(root){
current++;
nodes[current]=root;
root=root->lchild;
}
if(current){
root=nodes[current];
current--;
visit(root);
root=root->rchild;
}
}while(current);
}
后序遍历
后序遍历是二叉树三种非递归遍历中最难实现的,参考了网上的一些算法,都需要在栈中额外存储一组数据才可以实现,这里我设置了一个额外的数组flag[30]
来保存这些值。具体实现:
void BitTreeSearch_postorder(treenode* root){
do{
while(root){
current++;
nodes[current]=root;
root=root->lchild;
}
if(current){
if(flag[current]){ //数组flag[]被初始化为0
root=nodes[current];
flag[current]=0;
current--;
visit(root);
}
root=nodes[current];
falg[current]=1;
root=root->rchild;
}
}while(current);
}