二叉树的遍历
时间:2014-04-02 03:37 来源: 我爱IT技术网 作者:微风
最近正在学习C++编程语言。C++比C语言稍微难,个人理解,当然在C语言中指针也是很麻烦的。而且学习C语言的时候,没有任何编程基础,所以相对学习C++来说还是要难点。而C++是在C语言的基础上来学习的。因此简单的多。C语言是纯粹的面向过程。而C++则是半过程和半对象的。而java则是面向对象。在C++中对于数据结构方面。尤其是二叉树的学习,很有意思。下面是我参考相关的C++方面的书籍,所撰写的二叉树遍历的代码。分享给大家以助学习。
#include
#include
#include
typedef struct BiNode{
char data;
struct BiNode *l;
struct BiNode *r;
}BNode , *BTree; // struct BiNode =BNode
BTree Create(BTree T){
char ch;
ch=getchar();
if(ch=='#') //这个很重要,即如果没有子数都要用#填充
T=NULL;
else{
if(! (T=(BNode *)malloc(sizeof (BNode))) ) //一定是结构体类
printf("data error!");
T->data=ch;
T->l=Create(T->l);
T->r=Create(T->r);
}
return T;
};
void PreOder(BTree T){
if(T)
{
printf("%c",T->data);
PreOder(T->l);
PreOder(T->r);
}
};
void MidOder(BTree T){
if(T)
{
MidOder(T->l);
printf("%c",T->data);
MidOder(T->r);
}
};
int max(int a,int b)
{
if(a>b) return a;
else return b;
};
int height (BTree T)
{ int a;
int h2;
if(T==NULL) return 0;
else
{
h1=height(T->l);
h2=height(T->r);
return max(a,h2)+1; //函数也可以不再main 中声名而直接调用
//if(h1>h2)
// return h1+1;
//return h2+1;
}
};
// int findheight(BTree T, int x, int i)
//{ //BTree T;
//
// if (T==NULL)
// return 0;
//
// else{
// i++; //i 在主函数中为零 要调试
// if(T->data==x)
//
//
// findheight(T->l,x,i);
// findheight(T->r,x,i);
// }
// return i;
// }
void main(){
int a,b,x;
int i=0;
BTree t;
t=NULL;
t=Create(t); //也用递归 创建
PreOder(t);
printf("\n");
MidOder( t);
a= height (t);
printf("\n %d",a);
printf("\ninput the x to find" );
scanf("%d",&x );
//b= findheight ( t,x,i);
// printf("\n xis %d",b);
}
本文来源 我爱IT技术网 http://www.52ij.com/jishu/4704.html 转载请保留链接。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
