2123 求二叉树的高和宽

描述

以二叉链表为存储结构,分别写出求二叉树高度及宽度的算法,所谓宽度是指二叉树的各层上,具有结点数最多的那一层上的结点总数。

输入

括号表示的二叉树,如:

A(B,C)

输出

二叉树的高度和宽度,用空格分隔,如:

2 2

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
	char data;
	struct node*lchild;
	struct node*rchild;
}tree;
char s[1001];
int cnt=0;
tree* creattree()
{
	char c=s[cnt];
	tree* link = (tree*)malloc(sizeof(tree));
	while(c!=')')
	{
		if(c>='A'&&c<='Z')
		{
			link->data=c;
			link->lchild=NULL;
			link->rchild=NULL;
			cnt++;
			c=s[cnt];
		}
		if(c=='(')//疑似有左孩子
		{
			cnt++;
			if(s[cnt]!=',')//左孩子不空,创建左子树
			link->lchild=creattree();
			c=s[cnt];
			if(c==',')//疑似有右孩子
			{
				cnt++;
				if(s[cnt]==')')//右孩子空的
				{
					cnt++;
					return link;
				}
				link->rchild=creattree();
				cnt++;
				if(cnt>=(int)strlen(s))
					break;
				c=s[cnt];
			}
		}
		if(c==',')//遇到右孩子前面的一个节点,先返回父节点
		{
			return link;
		}
	}
	return link;
}
int maxdepth=0;//最大层数
void depth(tree* head,int d)//深度,d表示当前层数
{
	if(d>maxdepth)maxdepth=d;
	if(head->lchild!=NULL)
	{
		d++;
		depth(head->lchild,d);
		d--;
	}
	if(head->rchild!=NULL)
	{
		d++;
		depth(head->rchild,d);
		d--;
	}
}
int wid[1001],maxwid=0;//wid[i]表示第i层拥有的节点个数
int curdepth=0;//当前在树中的层数
void width(tree* head)//宽度
{
	wid[curdepth]++;
	if(wid[curdepth]>maxwid)maxwid=wid[curdepth];
	if(head->lchild!=NULL)
	{
		curdepth++;
		width(head->lchild);
		curdepth--;
	}
	if(head->rchild!=NULL)
	{
		curdepth++;
		width(head->rchild);
		curdepth--;
	}
}
int main()
{
	scanf("%s",s);
	tree*head=creattree();
	depth(head,1);
	memset(wid,0,sizeof(wid));
	width(head);
	printf("%d %d",maxdepth,maxwid);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值