ホームページ  >  記事  >  バックエンド開発  >  C 言語では、指定されたレベルのリーフ ノードを出力します。

C 言語では、指定されたレベルのリーフ ノードを出力します。

王林
王林転載
2023-08-25 14:17:12970ブラウズ

このタスクには、ユーザーが指定したレベル k でバイナリ ツリーのリーフ ノードを出力することが含まれます。

リーフ ノードは、左右のポインタが NULL であるエンド ノードです。つまり、特定のノードは NULL ではありません。

Example

の中国語訳は次のとおりです:

Example

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

C 言語では、指定されたレベルのリーフ ノードを出力します。

ここで、k はツリーのレベルを表します。印刷する必要があります。ここで使用される方法は、各ノードをループして、ノードにポインターがあるかどうかを確認することです。左または右、または両方を示すポインタが 1 つしかない場合でも、その特定のノードをリーフ ノードにすることはできません。

階層トラバーサル手法を使用して、左から始めてルート ノード、最後に右に各ノードを再帰的にトラバースします。

次のコードは、特定のアルゴリズムの 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

Example

中国語への翻訳は次のとおりです:

Example

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</p><p>",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;
}

出力

上記のプログラムを実行すると、次の出力が生成されます。

えええええ

以上がC 言語では、指定されたレベルのリーフ ノードを出力します。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。