ในปัญหานี้ เราได้รับไบนารีทรีและเราต้องพิมพ์โหนดลีฟทั้งหมดของแผนผังไบนารีจากซ้ายไปขวาด้วยวิธีวนซ้ำ
มาดูตัวอย่างทำความเข้าใจปัญหากัน
ป้อนข้อมูล -

ผลผลิต − 1 4 7
ในการแก้ปัญหานี้โดยใช้วิธีการวนซ้ำ เราจะใช้การค้นหาเชิงลึก (DFS) สำหรับ Traverse tree เราจะเริ่มจาก root node และตรวจสอบว่าเป็น leaf node หรือไม่ หากเป็นโหนดที่พิมพ์แล้ว โหนดอื่นจะค้นหาแผนผังย่อยและสำรวจทรีย่อยย่อยเพื่อค้นหา leaf nodes ทั้งหมด
ตัวอย่าง
รหัสด้านล่างจะใช้โซลูชันของเรา -
#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