暂时实现了计算最大深度和宽度,输入内容第一行是接下来的行数,接下来的每一行包括两个数字,从1开始计数,第i行两个数字表示编号为i的节点下的左右孩子的编号。
以下放代码:
开头:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int wide[256];//记录每一层的宽度
static int pos=1;//记录递归所走到的层数
typedef struct bintree
{
int no;//编号
struct bintree* left;//左孩子
struct bintree* right;//右孩子
}bintree;
寻找节点(i)在哪里:
int find(bintree *root,int i,int left,int right)
{
bintree *cur=root;//创建cur指针,最初从根节点进入
if(cur==NULL)//递归初始条件
return 0;
if(cur->no==i){
create(cur,left,right);//找到了就在这里创建吧
return 1;
}
else{
pos++;//要往下走一层,先加了再说
if(!find(cur->left,i,left,right))//左边没找到去右边找,pos不用减那么快,反正还要进去
find(cur->right,i,left,right);
pos--; //递归结束一次回来吧
}
return 0;
}
创建新节点
void create(bintree *cur,int left,int right){
if(left){
bintree *newleft=(bintree*)malloc(sizeof(bintree));
memset(newleft,0,sizeof(bintree));
cur->left=newleft;
newleft->no=left;
wide[pos]++;//那这一层就多了一个节点
}
if(right){
bintree *newright=(bintree*)malloc(sizeof(bintree));
memset(newright,0,sizeof(bintree));
cur->right=newright;
newright->no=right;
wide[pos]++;//同上
}
}
很渣的算宽度和深度
int max(int *wide){
int i,max=0;
for(i=1;wide[i]!=0;i++)
max=max>wide[i]?max:wide[i];
return max;
}
int big(int *wide){
int i,max=0;
for(i=1;wide[i]!=0;i++)
max++;
return max;
}
main函数如下:
int main ()
{ int i,exam,width,depth,left,right;
bintree *root=(bintree*)malloc(sizeof(bintree));
memset(root,0,sizeof(bintree));
root->no=1;
wide[pos]=1;
pos++;//根节点第一次递归有点不同的,要先加
scanf("%d",&exam);
for(i=1;i<=exam;i++){
scanf("%d%d",&left,&right);
find(root,i,left,right);
}
width=max(wide);
depth=big(wide);
printf("%d %d",width,depth);
}
转载自http://www.cnblogs.com/shenben/p/5516842.html
很棒的计算代码:
#include<cstdio>
#include<iostream>
using namespace std;
int a[30][3],b[30];
int main(){
int n,x,y,k,wide=0,deep=0;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d",&x,&y);
a[i][0]=x;a[i][1]=y;//储存左右孩子
a[x][2]=i;a[y][2]=i;//储存其父节点
}
for(int i=1;i<=n;i++){
k=1;
x=a[i][2];
while(x!=0){
k++;
x=a[x][2];
}
b[k]++;
if(k>deep) deep=k;
if(b[k]>wide) wide=b[k];
}
printf("%d %d\n",wide,deep);
//wide--最下一层的宽度(上一层的某节点最多有几个孩子);deep--深度
return 0;
}