यह ट्री के केवल विषम-स्तरीय लेवल प्रिंट करने के लिए एक C++ प्रोग्राम है।
एल्गोरिदम
स्ट्रक्चर और फंक्शन्स स्यूडोकोड के साथ:
Begin
nod को एक स्ट्रक्चर के रूप में घोषित करें।
d को इंटीजर डेटा टाइप के रूप में घोषित करें।
स्ट्रक्चर nod के विरुद्ध एक पॉइंटर l घोषित करें।
स्ट्रक्चर nod के विरुद्ध एक पॉइंटर r घोषित करें।
फंक्शन struct nod* newNod(int d) कॉल करें।
फंक्शन struct nod* newNod(int d) घोषित करें।
स्ट्रक्चर नोड के विरुद्ध एक पॉइंटर नोड घोषित करें।
नोड = (struct nod*) malloc(sizeof(struct nod)) आरंभ करें।
node->d = d
node->l = NULL
node->r = NULL
नोड लौटाएं।
फंक्शन printLevel(struct nod* root, int lvl) कॉल करें।
फंक्शन printLevel(struct nod* root, int lvl) घोषित करें।
if (root == NULL) तो
return
if (lvl == 1) तो
root->d के मान प्रिंट करें
else if (lvl > 1)
printLevel(root->l, lvl - 1) कॉल करें
printLevel(root->r, lvl - 1) कॉल करें
फंक्शन height(struct nod* node) कॉल करें।
फंक्शन 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)
फंक्शन printLevelOrder(struct nod* root) घोषित करें।
h को इंटीजर डेटा टाइप के रूप में घोषित करें।
h = height(root) आरंभ करें।
i को इंटीजर डेटा टाइप के रूप में घोषित करें।
for (i = 1; i <= h; i+=2)
फंक्शन printLevel(root, i) कॉल करें।
ट्री में मान डालें।
"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* 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);
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);
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);
int i;
for (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