二叉树的前序建立方式

来源:互联网 发布:贪婪洞窟淘宝刷钻石 编辑:程序博客网 时间:2024/06/06 12:57
</pre><pre name="code" class="cpp">#include<iostream>#include<cstdlib>#include<cstdio>using namespace std;typedef struct BiTNode{char data;struct BiTNode *lchild,*rchild;}*BiTree;//创建一课二叉树,根左右方式输入数据 void CreateTree(BiTree &T){char c;c=getchar();if(c==' '){T=NULL;}else{T=(BiTNode *)malloc(sizeof(BiTNode));/*T=(BiTree)malloc(sizeof(BiTNode));*//*T=(BiTree)malloc(sizeof(BiTree));这种是错误的,不知道可以百度结构体的不同写法*/ T->data=c;CreateTree(T->lchild);CreateTree(T->rchild);}} void Vist(char c,int level){cout<<c<<"位于第"<<level<<"层."<<endl; }void PreView(BiTree T,int level)//递归遍历 {if(T){Vist(T->data,level);PreView(T->lchild,level+1);PreView(T->rchild,level+1);}}int CountLeaf(BiTree T)//统计叶子节点个数 {int countleft,countright;if(T==NULL){return 0;}if(T->lchild==NULL&&T->rchild==NULL){return 1;}countleft=CountLeaf(T->lchild);countright=CountLeaf(T->rchild);return countleft+countright;} int CountDepth(BiTree T)//计算二叉树深度 {int countleft,countright;if(T==NULL){return 0;}else{countleft=CountDepth(T->lchild);countright=CountDepth(T->rchild);if(countleft>=countright){return countleft+1;}else{return countright+1;}}}BiTNode *SearchNode(BiTree T,char e)//查找某个节点的位置 {if(T==NULL){cout<<"树空,没有元素!"<<endl;return NULL;}if(T->data==e){cout<<"元素找到了:"<<T->data<<endl; return T;}BiTNode *p;p=SearchNode(T->lchild,e);if(p) return p;//俗称的剪枝 p=SearchNode(T->rchild,e);if(p) return p;//俗称的剪枝 } int main(){int level=1;BiTree T=NULL;    CreateTree(T);    PreView(T,level);    cout<<endl<<"叶子节点个数为:"<<CountLeaf(T)<<endl;    cout<<endl<<"二叉树的深度为:"<<CountDepth(T)<<endl;     char code='D';    SearchNode(T,code);    return 0;}


0 0
原创粉丝点击