在C語言中列印完美二叉樹的中間層,無需查詢高度


程式應該列印二叉樹的中間層,例如,如果二叉樹有4層,那麼程式必須列印第2層的節點,但這裡要求是在不查詢高度的情況下計算層數。

完美二叉樹是指內部節點必須有兩個子節點,並且所有葉子節點都應在同一層或深度。

這裡:

  • 內部節點21和32都有子節點。

  • 葉子節點是41、59、33和70,它們都在同一層。

因為它滿足這兩個屬性,所以它是一個完美的二叉樹。

示例

Input : 12 21 32 41 59 33 70
Output : 21 32

這裡使用的方法就像查詢連結串列的中間元素一樣,透過檢查節點的左指標和右指標是否為NULL來進行遞迴呼叫函式。

下面的程式碼顯示了給定演算法的C語言實現。

演算法

START
   Step 1 -> create node variable of type structure
      Declare int key
      Declare pointer of type node using *left, *right
   Step 2 -> create function for inserting node with parameter as value
      Declare temp variable of node using malloc
      Set temp->data = value
      Set temp->left = temp->right = NULL
      return temp
   step 3 - > Declare Function void middle(struct Node* a, struct Node* b)
      IF a = NULL||b = NULL
         Return
      IF ((b->left == NULL) && (b->right == NULL))
         Print a->key
         Return
      End
      Call middle(a->left, b->left->left)
      Call middle(a->right, b->left->left)
   Step 4 -> Declare Function void mid_level(struct Node* node)
      Call middle(node, node)
   Step 5 -> In main()
      Call New passing value user want to insert as struct Node* n1 = New(13);
      Call mid_level(n1)
STOP

示例

#include <stdio.h>
#include<stdlib.h>
struct Node {
   int key;
   struct Node* left, *right;
};
struct Node* New(int value) {
   struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
   temp->key = value;
   temp->left = temp->right = NULL;
   return (temp);
}
void middle(struct Node* a, struct Node* b) {
   if (a == NULL || b == NULL)
      return;
   if ((b->left == NULL) && (b->right == NULL)) {
      printf("%d ",a->key);
      return;
   }
   middle(a->left, b->left->left);
   middle(a->right, b->left->left);
}
void mid_level(struct Node* node) {
   middle(node, node);
}
int main() {
   printf("middle level nodes are : ");
   struct Node* n1 = New(13);
   struct Node* n2 = New(21);
   struct Node* n3 = New(44);
   struct Node* n4 = New(98);
   struct Node* n5 = New(57);
   struct Node* n6 = New(61);
   struct Node* n7 = New(70);
   n2->left = n4;
   n2->right = n5;
   n3->left = n6;
   n3->right = n7;
   n1->left = n2;
   n1->right = n3;
   mid_level(n1);
}

輸出

如果我們執行上面的程式,它將生成以下輸出。

middle level nodes are : 21 44

更新於:2019年8月22日

162 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.