C語言中列印指定層級的葉子節點


此任務涉及列印給定級別 k(由使用者指定)的二叉樹的葉子節點。

葉子節點是左右指標都為 NULL 的末端節點,這意味著該特定節點不是父節點。

示例

Input : 11 22 33 66 44 88 77
Output : 88 77

這裡,k 表示需要列印的樹的級別。此處使用的方法是遍歷每個節點並檢查該節點是否具有任何指標。即使只有一個指標(這意味著左指標或右指標或兩者都有),該特定節點也不能是葉子節點。

使用層序遍歷技術遞迴遍歷每個節點,其中節點從左→根→右逐層遍歷。

以下程式碼顯示了給定演算法的 C 實現

演算法

START
   Step 1 -> create node variable of type structure
      Declare int data
      Declare pointer of type node using *left, *right
   Step 2 -> create function for inserting node with parameter as new_data
      Declare temp variable of node using malloc
      Set temp->data = new_data
      Set temp->left = temp->right = NULL
      return temp
   Step 3 -> declare Function void leaf(struct node* root, int level)
      IF root = NULL
         Exit
      End
      IF level = 1
         IF root->left == NULL && root->right == NULL
            Print root->data
         End
      End
      ELSE IF level>1
         Call leaf(root->left, level - 1)
         Call leaf(root->right, level - 1)
      End
   Step 4-> In main()
      Set level = 4
      Call New passing value user want to insert as struct node* root = New(1)
      Call leaf(root,level)
STOP

示例

include<stdio.h>
#include<stdlib.h>
//structre of a node defined
struct node {
   struct node* left;
   struct node* right;
   int data;
};
//structure to create a new node
struct node* New(int data) {
   struct node* temp = (struct node*)malloc(sizeof(struct node));
   temp->data = data;
   temp->left = NULL;
   temp->right = NULL;
   return temp;
}
//function to found leaf node
void leaf(struct node* root, int level) {
   if (root == NULL)
      return;
   if (level == 1) {
      if (root->left == NULL && root->right == NULL)
      printf("%d
",root->data);    } else if (level > 1) {       leaf(root->left, level - 1);       leaf(root->right, level - 1);    } } int main() {    printf("leaf nodes are: ");    struct node* root = New(11);    root->left = New(22);    root->right = New(33);    root->left->left = New(66);    root->right->right = New(44);    root->left->left->left = New(88);    root->left->left->right = New(77);    int level = 4;    leaf(root, level);    return 0; }

輸出

如果執行上述程式,則會生成以下輸出。

leaf nodes are: 88 77

更新於:2019年8月22日

871 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告