结构推理 写一个算法,计算一棵二叉树的结点数及树的高度。
【正确答案】(1)数据结构
   采用二叉树的链接表示。
   (2)思路
   先根周游二叉树,统计出结点的个数,并统计结点层数的最大值。
   (3)算法
   int calculate(BinTree t,int*pdepth,int*pheight){    /*辅助函数*/
   /*计算子树t结点个数,整数(*pdepth)为t根结点的层数,整数(*pheight)为当前树的高度*/
       int temp1,temp2;
       if(t==NULL){
           (*pdepth)--;
           return 0:
       }
       if((*pdepth)>(*pheight))(*pheight)=(*pdepth);
           /*当前结点的深度大于树的高度时,将树的高度置为当前结点的深度*/
       (*pdepth)++;
       temp 1=calculate(t->llink,pdepth,pheight);/*计算左子树*/
       (*pdepth)++;
       temp2=calculate(t->rlink,pdepth,pheight);   /*计算右子树*/
       (*pdepth)--;
       return 1+temp1+temp2;    /*结点个数等于1加上左右子树结点个数之和*/
   }
   int nodes_height(BinTree t,int*pheight){    /*计算二叉树的结点个数及高度*/
       int depth=0:
       (*pheight)=0;
       return calculate(t,&depth,pheight);
   }
   (4)代价分析
   该算法访问每个结点各一次,时间代价为O(n),空间代价为O(h)。
【答案解析】这道题可以设计成两个递归函数,功能分别为:计算二叉树的结点数和计算二叉树的高度,然后用一个主函数依次调用它们。