数据结构实验之二叉树的建立与遍历


这道题的算法思想就是利用好递归的思想建立二叉树,然后对二叉树进行操作。

代码如下:

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值