Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

พิมพ์ระดับของโหนดทั้งหมดใน Binary Tree ในการเขียนโปรแกรม C++


จากไบนารีทรี ภารกิจคือการพิมพ์ระดับที่เกี่ยวข้องกับทุกคีย์ที่จัดเก็บไว้ในโหนดโดยเริ่มจาก 1 ถึง n

พิมพ์ระดับของโหนดทั้งหมดใน Binary Tree ในการเขียนโปรแกรม C++

ในทรีข้างต้น โหนดคือ −

10 ที่ระดับ 13 และ 211 ที่ระดับ 2140, 162, 100 และ 146 ที่ระดับ 3

เมื่อได้รับคีย์ โปรแกรมจะต้องพิมพ์ระดับของคีย์นั้นๆ

ตัวอย่าง

Input:10 3 211 140 162 100 146Output:ระดับ 10 คือ 1 ระดับ 3 คือ 2 ระดับ 211 คือ 2 ระดับ 140 คือ 3 ระดับ 162 คือ 3 ระดับ 100 คือ 3 ระดับ 146 คือ 3 

อัลกอริทึม

STARTStep 1 -> สร้างโครงสร้างของโหนดเป็น struct node struct node *left, *right int data EndStep 2 -> ฟังก์ชั่นสร้างโหนดโหนด* newnode(int data) node *temp =new node temp-> data =data temp->left =temp->right=NULL return tempstep 3 -> สร้างฟังก์ชันสำหรับค้นหาระดับของระดับโหนดที่เป็นโมฆะ (Node* root) IF root=NULL Return End สร้างคิว STL>que que.push({root, 1}) สร้างคู่ STL par Loop ขณะที่ !que.empty() par =que.front() que.pop() พิมพ์ par.first->data และ par.second IF par.first->left que.push({ par.first->left, par.second + 1 }) END IF par.first->right que.push ({ par.first-> right, par.second + 1 }) สิ้นสุด EndSTOP

ตัวอย่าง

#include ใช้เนมสเปซ std;// โครงสร้างของโหนด nodestruct { ข้อมูล int; struct Node *left, *right;}; // จะพิมพ์ระดับของระดับ treevoid (โหนด * root) { if (root==NULL) กลับมา; คิว >que; que.push({ราก, 1}); คู่ พาร์; ในขณะที่ (!que.empty()) { ตราไว้หุ้นละ =que.front(); que.pop(); cout <<"ระดับของ" <data <<" คือ " <left) que.push({ par.first->left, par.second + 1 }); ถ้า (par.first->right) que.push({ par.first->right, par.second + 1 }); }}//ฟังก์ชันเพื่อสร้างโหนดและสร้าง treeNode* newnode(int data){ Node* temp =new Node; temp->data =ข้อมูล; temp->left =temp->right =NULL; return temp;}int main(){ โหนด* root =NULL; // มันจะสร้างโหนด root =newnode(34); root->left =newnode(12); รูท -> ขวา =โหนดใหม่ (50); root->left->left =newnode(11); root->left->right =newnode(54); ระดับ(ราก); คืนค่า 0;}

ผลลัพธ์

หากเรารันโปรแกรมข้างต้น มันจะสร้างผลลัพธ์ดังต่อไปนี้

ระดับ 34 คือ 1ระดับ 12 คือ 2ระดับ 50 คือ 2ระดับ 11 คือ 3ระดับ 54 คือ 3