chap 6 樹和二叉樹(程序填空題)

下列代碼的功能是計算給定二叉樹T的寬度。二叉樹的寬度是指各層結點數的最大值。函數Queue_rearQueue_front分別返回當前隊列Q中隊尾和隊首元素的位置。

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); 
         temp_width++;//(3分) 
         if ( p->Left != NULL )  Enqueue(p->Left, Q);
         if ( p->Right != NULL )  Enqueue(p->Right, Q);//(3分);  
         if ( Queue_front(Q) > Last ) {
            Last = Queue_rear(Q);
            if ( temp_width > max_width ) max_width = temp_width;
            temp_width = 0;//(3分);
         } /* end-if */
      } /* end-while */
      return  max_width;
   } /* end-else */
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章