数据结构实验之二叉树的建立与遍历
2016-08-08 19:55
495 查看
这道题的算法思想就是利用好递归的思想建立二叉树,然后对二叉树进行操作。
代码如下:
#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;
}
相关文章推荐
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- SDUT-2136数据结构实验之二叉树的建立与遍历
- sdut 2136 数据结构实验之二叉树的建立与遍历(二叉树遍历,叶子数和深度)
- SDUTOJ 2136 数据结构实验之二叉树的建立与遍历
- SDUT-2136 数据结构实验之二叉树的建立与遍历
- 数据结构实验之 二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 【二叉树的建立和遍历】SDUTOJ 2136---数据结构实验之二叉树的建立与遍历
- 2136 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历
- SDUT 2136 数据结构实验之二叉树的建立与遍历