二叉树的基本操作 C++
大家对二叉数的数据存储结构相比并不陌生,今天向大家介绍一下二叉数的基本操作:包括(1)、二叉树的先序建立。(2)先、中、后序遍历(3)层序遍历(4)树的深度 (5)、对叶子进行层序的遍历输出 (6)、统计叶子的数目(7)、根据先序遍历以及中序遍历还原二叉树 (8)、根据中序遍历以及后序遍历还原二叉树
以下为函数代码的解释:
int Depth(Tree *T);//求二叉树的深度 void Pre_Order(Tree *T);//先序遍历二叉树 void In_Order(Tree *T);//中序遍历二叉树 void Pos_Order(Tree *T);//后序遍历二叉树 int CountLef(Tree *T);//统计叶子的数目(层序遍历为基础) void PrintLef(Tree *T);//打印每个叶子(层序遍历的顺序) Tree *PreCreat(char a[]);//先序建立二叉树 Tree *Pre_In_Order(int n,char a[],char b[]);//根据先序以及中序遍历还原二叉树 Tree *In_Pos_Order(int n,char a[],char b[]);//根据中序以及后序遍历还原二叉树
下面为代码:
#include <bits/stdc++.h> using namespace std; struct Tree { char data; Tree *lchild,*rchild; }; int iq=0; int Depth(Tree *T); void Pre_Order(Tree *T); void In_Order(Tree *T); void Pos_Order(Tree *T); int CountLef(Tree *T); void PrintLef(Tree *T); Tree *PreCreat(char a[]); Tree *Pre_In_Order(int n,char a[],char b[]); Tree *In_Pos_Order(int n,char a[],char b[]); int main() { char a[100]; int n; while(cin>>a) { Tree *TT=PreCreat(a); Pre_Order(TT); } return 0; } Tree *PreCreat(char a[]) { Tree *T; if(a[iq]==,) { T=NULL; iq++; } else { T=new Tree; T->data=a[iq]; iq++; T->lchild=PreCreat(a); T->rchild=PreCreat(a); } return T; } void Pre_Order(Tree *T) { if(T!=NULL) { cout<<T->data; Pre_Order(T->lchild); Pre_Order(T->rchild); } } void In_Order(Tree *T) { if(T!=NULL) { In_Order(T->lchild); cout<<T->data; In_Order(T->rchild); } } void Pos_Order(Tree *T) { if(T!=NULL) { Pos_Order(T->lchild); Pos_Order(T->rchild); cout<<T->data; } } Tree *Pre_In_Order(int n,char a[],char b[]) { int i; Tree *T; if(n<=0) T=NULL; else { T=new Tree; T->data=*a; for(i=0;i<n;i++) if(b[i]==*a) break; T->lchild=Pre_In_Order(i,a+1,b); T->rchild=Pre_In_Order(n-i-1,a+i+1,b+i+1); } return T; } Tree *In_Pos_Order(int n,char a[],char b[]) { int i; Tree *T; if(n<=0) { T=NULL; } else { T=new Tree; T->data=b[n-1]; for(i=0;i<n;i++) if(a[i]==b[n-1]) break; T->lchild=In_Pos_Order(i,a,b); T->rchild=In_Pos_Order(n-i-1,a+i+1,b+i); } return T; } void PrintLef(Tree *T) { Tree *p[100]; int a=0,b=1; p[a]=T; while(a<b) { if(p[a]) { if(p[a]->lchild==NULL&&p[a]->rchild==NULL) { cout<<p[a]->data; } p[b++]=p[a]->lchild; p[b++]=p[a]->rchild; } a++; } } int CountLef(Tree *T) { Tree *p[100]; int a=0,b=1,Count=0; p[a]=T; while(a<b) { if(p[a]) { if(p[a]->lchild==NULL&&p[a]->rchild==NULL) Count++; p[b++]=p[a]->lchild; p[b++]=p[a]->rchild; } a++; } return Count; } int Depth(Tree *T) { if(T==NULL) return 0; else { return 1+(Depth(T->lchild)>Depth(T->rchild))?Depth(T->lchild):Depth(T->rchild); } }
下一篇:
LC刷题-花园最大的总美丽值