typedef struct node{
int data;
node *left;
node *right;
}Node,*Tree;
求二叉树的宽度。宽度:有结点数最多的那一层的结点个数。
void order(Tree tree,int lay, int a[]){ //二叉树,层数,辅助数组
if(node->left!= nullptr){
order(node->left,lay+1,a);
}
if(node->right!= nullptr){
order(node->right,lay+1,a);
}
a[lay] = a[lay]+ 1; //辅助数组,标记同一层的结点数量
}
//求二叉树的宽度
int getWidth(Tree tree,int h){ //h二叉树的高度
int* a=(int *)malloc(sizeof(int)*h); //初始化数组
for(int j =0;j<h;j++){
a[j] = 0;
}
order(node,0,a); //遍历二叉树
int width = a[0]; //找出数组最大的值
for(int i =1;i<h;i++){
if(a[i]>width){
width = a[i];
}
}
return width; //返回宽度
}
求二叉树测深度。
//计算二叉树的深度
int getDepth(Tree tree,int depth){
int i=depth,j=depth; //初始化i,j左右子树深度与当前结点深度相同
if(tree->left != nullptr){
i = getDepth(tree->left,depth+1); //i左子树深度
}
if(tree->right != nullptr){
j = getDepth(tree->right,depth+1); //i左子树深度
}
if(i>depth|| j>depth){ //返回三者值最大的作为已遍历子树的深度
if(i>j){
return i;
}
else{return j;};
}
else{
return depth;
}
}