C++ program to find minimum in binary tree














































C++ program to find minimum in binary tree



/**C++ program to find minimum in binary tree**/
/** A binary tree is a non-linear data structure in which each node has maximum of two child nodes.To
find the smallest element we have go through all the element first just like searching in a array
(different from binary search tree).
For finding minimum element of the binary tree we need to consider root node value as minimum
Then we will check both child of the node if data of any of the node is less than the minimum
value then minimum value will be updated by that node .
In this program we need to check for each node once so time complexity of the program will be
O(n) where 'n' is the total no of node of the binary tree.**/
//Program:
#include<iostream> #include<queue> using namespace std; struct Node { int data; struct Node* left, *right; }; struct Node* newNode(int value) { struct Node* temp =new Node; temp->data = value; temp->left = temp->right = NULL; return temp; }; /**Insertion of new node in the binary tree**/ void insert(struct Node* temp, int value) { queue<struct Node*> q; q.push(temp); while(!q.empty()) { struct Node* temp = q.front(); q.pop(); if(!temp->left) { temp->left = newNode(value); break; } else q.push(temp->left); if (!temp->right) { temp->right = newNode(value); break; } else q.push(temp->right); } } /**Finding minimum value of the binary tree**/ int min_element(struct Node* root, int &min) { struct Node *temp=root; if(temp->left!=nullptr || temp->right!=nullptr) if(temp->data<min) min=temp->data; if(temp->left==nullptr && temp->right==nullptr) return min; else { min=min_element(temp->left, min); min=min_element(temp->right, min); } return min; } int main() { int value,t,s; struct Node* root = newNode(8); //Insertion of elements; root->left = newNode(2); root->left->left = newNode(3); root->right = newNode(5); root->right->left = newNode(12); root->right->right = newNode(11); root->left->right = newNode(7); root->left->left->left = newNode(16); t = 19; insert(root,t); int min=INT_MAX; min=min_element(root, min); cout << "Minimum element of the binary tree is: " << endl; cout << min; return 0; } /** Output: Minimum element of the binary tree is: 2 **/

Comments