数据结构/PTA-树的宽度/树/填空题

typedef struct TreeNode *BinTree;
struct TreeNode
{
   int Key;
   BinTree  Left;
   BinTree  Right;
};

int Width( BinTree T )
{
   BinTree  p;
   Queue Q;
   int Last, temp_width, max_width;

   temp_width = max_width = 0;
   Q = CreateQueue(MaxElements);
   Last = Queue_rear(Q);
   if ( T == NULL) return 0;
   else {
      Enqueue(T, Q);
      while (!IsEmpty(Q)) {
         p = Front_Dequeue(Q); 
         
___________________________
; 
         if ( p->Left != NULL )  Enqueue(p->Left, Q);
         
 ___________________________
;  
         if ( Queue_front(Q) > Last ) {
            Last = Queue_rear(Q);
            if ( temp_width > max_width ) max_width = temp_width;
            
_____________________________
;
         } /* end-if */
      } /* end-while */
      return  max_width;
   } /* end-else */
} 

 下列代码的功能是计算给定二叉树T的宽度。二叉树的宽度是指各层结点数的最大值。函数Queue_rear和Queue_front分别返回当前队列Q中队尾和队首元素的位置。

 

注意:Queue_rear和Queue_fron返回的是位置,位置,位置。

代码部分:前半部分,设置变量,树、队列、队尾位置、两个宽度变量

                  后半部分,判空,树入队,开始求宽度

                           首先队头出队,宽度肯定是+1的

                           左右子树入队,这一步和上一步就是不断地拆树

                           如果到了队尾,就更新最大宽度

填写:

 temp_width++; 


if ( p->Right != NULL )  Enqueue(p->Right, Q);  


temp_width=0;

第二三个空肯定是好写的,第二个就是举一反三,第三个是要把临时宽度归零

主要是看第一个空的理解

         

posted @ 2020-10-25 20:10  EleclouD  阅读(552)  评论(0编辑  收藏  举报