ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อพิมพ์โหนดที่อยู่ในระดับคี่ของไบนารีทรีที่กำหนด
ในโปรแกรมนี้ ระดับของโหนดรูทถือเป็น 1 และระดับทางเลือกถัดไปจะเป็นระดับคี่ถัดไปพร้อมกัน
ตัวอย่างเช่น สมมติว่าเราได้รับด้วยไบนารีทรีต่อไปนี้

จากนั้นโหนดที่ระดับคี่ของไบนารีทรีนี้จะเป็น 1, 4, 5, 6
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left, *right;
};
//printing the nodes at odd levels
void print_onodes(Node *root, bool is_odd = true){
if (root == NULL)
return;
if (is_odd)
cout << root->data << " " ;
print_onodes(root->left, !is_odd);
print_onodes(root->right, !is_odd);
}
//creating a new node
struct Node* create_node(int data){
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
int main(){
struct Node* root = create_node(13);
root->left = create_node(21);
root->right = create_node(43);
root->left->left = create_node(64);
root->left->right = create_node(85);
print_onodes(root);
return 0;
} ผลลัพธ์
13 64 85