【数据结构】二叉树的前序遍历建立及计算深度

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
//二叉树的存储结构,一个数据域,2个指针域
typedef struct tree	
{
	char data;//数据域
	struct tree *lchild;//左子节点
	struct tree *rchild;//右子节点
}Bitree;


//创建一棵二叉树
Bitree *CreateBitree()
	//返回值为Bitree类型的名为CreateBitree的函数,传入参数为Bitree类型的T的地址
{   Bitree *T;
	char ch;
	scanf("%c",&ch);
	if(ch=='$') 
		return NULL;//若输入为空,结点为空
	else
		//若不为空,创建结点
	{   
		T=(Bitree *)malloc(sizeof(Bitree));//分配存储空间
		T->data=ch;
		T->lchild=CreateBitree();
		T->rchild=CreateBitree();
        return T; 
	}
}
//递归实现二叉树的深度
int treedepth(Bitree *T)
{
	int rd=0,ld=0;
	if(T!=NULL)
	{
		//找到最左边的左右孩子为空的结点,之后找到相对位置靠近第一个结点的结点
		ld=treedepth(T->lchild)+1;
		rd=treedepth(T->rchild)+1;
	}
	return ld>=rd?ld:rd;//取左右深度最大值为二叉树的深度
}

int main(void)
{
	Bitree *T;//创建根节点
    //printf("请以先序输入二叉树($表示该结点的子结点为空):\n");
    T=CreateBitree();
    int deep=treedepth(T);//创建整形变量deep调用treedepth函数,将二叉树T传过去
    printf("%d\n",deep);
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值