এটি একটি C++ প্রোগ্রাম যা ট্রির শুধু বিষম নম্বরযুক্ত লেভেল প্রিন্ট করে।
অ্যালগরিদম
স্ট্রাকচার এবং ফাংশন প্রসিডিউর:
Begin
nod স্ট্রাকচার ঘোষণা করুন।
d ইন্টিজার টাইপে ঘোষণা করুন।
struct nod-এ l এবং r পয়েন্টার ঘোষণা করুন।
struct nod* newNod(int d) ফাংশন কল করুন।
ফাংশন ডিক্লেয়ার: newNod(int d)।
নোডের মেমরি অ্যালোকেট করুন, d সেট করুন, l এবং r NULL করুন, রিটার্ন করুন।
printLevel(struct nod* root, int lvl) ফাংশন কল করুন।
ফাংশন ডিক্লেয়ার: printLevel(struct nod* root, int lvl)।
height(struct nod* node) ফাংশন কল করুন ট্রির উচ্চতা জানতে।
printLevelOrder(struct nod* root) ফাংশন ডিক্লেয়ার করুন।
ট্রিতে মান ইনসার্ট করুন।
"Odd numbered Level Order traversal of binary tree is" প্রিন্ট করুন।
printLevelOrder(root) কল করুন।
Endউদাহরণ
#include <iostream>
#include <stdlib.h>
using namespace std;
struct nod {
int d;
struct nod* l;
struct nod* r;
};
struct nod* newNod(int d) {
struct nod* node = (struct nod*) malloc(sizeof(struct nod));
node->d = d;
node->l = NULL;
node->r = NULL;
return (node);
}
void printLevel(struct nod* root, int lvl) {
if (root == NULL) return;
if (lvl == 1) printf("%d ", root->d);
else if (lvl > 1) {
printLevel(root->l, lvl - 1);
printLevel(root->r, lvl - 1);
}
}
int height(struct nod* node) {
if (node == NULL) return 0;
else {
int lhght = height(node->l);
int rhght = height(node->r);
if (lhght > rhght) return (lhght + 1);
else return (rhght + 1);
}
}
void printLevelOrder(struct nod* root) {
int h = height(root);
for (int i = 1; i <= h; i += 2)
printLevel(root, i);
}
int main() {
struct nod* root = newNod(7);
root->l = newNod(6);
root->r = newNod(4);
root->l->l = newNod(3);
root->l->r = newNod(5);
root->r->l = newNod(2);
root->r->r = newNod(1);
cout << "Odd numbered Level Order traversal of binary tree is \n";
printLevelOrder(root);
return 0;
}আউটপুট
Odd numbered Level Order traversal of binary tree is 7 3 5 2 1