Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 반복적 접근을 사용하여 왼쪽에서 오른쪽으로 이진 트리의 모든 리프 노드 인쇄


이 문제에서는 이진 트리가 주어지고 이진 트리의 모든 리프 노드를 왼쪽에서 오른쪽으로 반복 접근 방식으로 인쇄해야 합니다.

문제를 이해하기 위해 예를 들어보겠습니다.

입력 -

C++에서 반복적 접근을 사용하여 왼쪽에서 오른쪽으로 이진 트리의 모든 리프 노드 인쇄

출력 − 1 4 7

반복적 접근을 사용하여 이 문제를 해결하기 위해 우리는 깊이 우선 탐색(DFS)을 사용할 것입니다. 트리를 트래버스하려면 루트 노드에서 시작하여 리프 노드인지 확인한 다음 노드를 인쇄하고 그렇지 않으면 자식 트리를 찾고 자식 하위 트리를 트래버스하여 모든 리프 노드를 찾습니다.

예시

아래 코드는 우리의 솔루션을 구현합니다 -

#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node *left, *right;
};
Node* insertNode(int data) {
   Node *temp = new Node;
   temp->data = data;
   temp->left = temp->right = NULL;
   return temp;
}
void printLTRLeafNodes(Node *root){
   if (!root)
      return;
   if (!root->left && !root->right) {
      cout<<root->data<<"\t";
      return;
   }
   if (root->left)
      printLTRLeafNodes(root->left);
   if (root->right)
      printLTRLeafNodes(root->right);
}
int main(){
   Node *root = insertNode(21);
   root->left = insertNode(5);
   root->right = insertNode(36);
   root->left->left = insertNode(2);
   root->right->left = insertNode(13);
   root->right->right = insertNode(4);
   root->right->left->left = insertNode(76);
   root->right->left->right = insertNode(9);
   root->right->right->left = insertNode(17);
   root->right->right->right = insertNode(2);
   cout<<"Leaf Nodes of the tree from left to rigth are :\n";
   printLTRLeafNodes(root);
   return 0;
}

출력

Leaf Nodes of the tree from left to right are −
2 76 9 17 2