数据结构实验之二叉树的建立与遍历
来源:互联网 发布:广告公司开单软件 编辑:程序博客网 时间:2024/06/05 07:21
这道题的算法思想就是利用好递归的思想建立二叉树,然后对二叉树进行操作。
代码如下:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char a[55];
int len,i;
struct node{/*二叉树的定义*/
char data;
struct node *lchild,*rchild;
};
struct node* Createtree(){/*按先序遍历的结果创建二叉树*/
struct node *root;
if(i<len){
char c=a[i++];
if(c==',')
return NULL;
else{
root=(struct node*)malloc(sizeof(struct node));
root->data=c;
root->lchild=Createtree();
root->rchild=Createtree();
}
}
return root;
};
void Zhongxu(struct node* root){/*中序遍历函数*/
if(root){
Zhongxu(root->lchild);
printf("%c",root->data);
Zhongxu(root->rchild);
}
}
void Houxu(struct node* root){/*后序遍历函数*/
if(root){
Houxu(root->lchild);
Houxu(root->rchild);
printf("%c",root->data);
}
}
int Leaves(struct node* root){/*求叶子结点函数*/
int num1,num2;
if(root==NULL)
return 0;
else{
if(root->lchild==NULL&&root->rchild==NULL)
return 1;
num1=Leaves(root->lchild);//求左子树中叶子节点数
num2=Leaves(root->rchild);//求右子树中叶子节点数
return num1+num2;
}
}
int Deeptree(struct node* root){/*二叉树深度函数*/
int i,j;
if(!root)
return 0;
i=Deeptree(root->lchild);/*求左子树的高度*/
j=Deeptree(root->rchild);/*求右子树的高度*/
if(i>j)
return i+1;
else
return j+1;
}
int main(){
struct node *root;
scanf("%s",&a);
len=strlen(a);
i=0;
root=Createtree();
Zhongxu(root);
printf("\n");
Houxu(root);
printf("\n");
printf("%d\n",Leaves(root));
printf("%d",Deeptree(root));
return 0;
}
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 2136 数据结构实验之二叉树的建立与遍历
- 2136 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- sdutoj2136 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历 SDUT
- 详细讲解HTML 5中视频和音频核心事件
- scala spark maven 配置文件 pom.xml
- java回忆录—I/O流详解补充
- RDD之aggregate操作
- JAVA 递归 汉诺塔
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树六:哈夫曼编码
- iOS 过滤输入Emoji表情的问题
- UE4编译专用服务器
- glassfish restful web service 配置文件 web.xml
- IDEA 15 破解
- SVN的操作步骤和使用
- UVa-11988-Broken Keyboard (a.k.a. Beiju Text)
- 最小生成树算法