यह बाइनरी सर्च ट्री का उपयोग करके सरणी के अधिकतम एलिमेंट को खोजने के लिए एक C++ प्रोग्राम है। इस प्रोग्राम की समय जटिलता O(log n) है।
एल्गोरिदम
शुरुआत दिए गए डेटा एलिमेंट्स का उपयोग करके बाइनरी सर्च ट्री बनाएं। अगला रूट पॉइंटर को दाएं सबसे चाइल्ड नोड पर ट्रैवर्स करें। नोड के डेटा भाग को दिए गए डेटा सेट के अधिकतम डेटा एलिमेंट के रूप में प्रिंट करें। अधिकतम डेटा की गहराई प्रिंट करें। अंत
उदाहरण कोड
#include<iostream> using namespace std; struct node { int d; node *left; node *right; }; node* CreateNode(int d) { node *newnode = new node; newnode->d = d; newnode->left = NULL; newnode->right = NULL; return newnode; } node* InsertIntoTree(node* root, int d) { node *temp = CreateNode(d); node *t = new node; t = root; if(root == NULL) root = temp; else { while(t != NULL){ if(t->d < d ) { if(t->right == NULL) { t->right = temp; break; } t = t->right; } else if(t->d > d) { if(t->left == NULL) { t->left = temp; break; } t = t->left; } } } return root; } int main() { int n, i, a[10] = {86, 63, 95, 6, 7, 67, 52, 26, 45, 98}; node *root = new node; root = NULL; cout<<"\nData set:\n"; for(i = 0; i < 10; i++) { cout<<a[i]<<" "; root = InsertIntoTree(root, a[i]); } cout<<"\n\nThe maximum element of the given data set is\n "; i = 0; while(root->right != NULL) { i++; root = root->right; } cout<<root->d<<"\n"<<"data found at "<<i<<" depth from the root."; return 0; } आउटपुट
Data set: 86 63 95 6 7 67 52 26 45 98 The maximum element of the given data set is 98 data found at 2 depth from the root.