이 작업은 사용자가 지정한 주어진 수준 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\n",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