maximum element in a binary tree

Solutions on MaxInterview for maximum element in a binary tree by the best coders in the world

showing results for - "maximum element in a binary tree"
Gael
16 Jan 2021
1#include<iostream>
2using namespace std;
3struct node
4{
5    int data;
6    node* left;
7    node* right;
8};
9node* getnode(int value)
10{
11    node* temp=new node;
12    temp->data=value;
13    temp->left=NULL;
14    temp->right=NULL;
15    return temp;
16}
17node* insert_bst(node* roots,int value)
18{
19    if(roots==NULL)
20    {
21        return getnode(value);
22    }
23    if(roots->data>value)
24    {
25        roots->left=insert_bst(roots->left,value);
26    }
27    else if(roots->data<value)
28    {
29        roots->right=insert_bst(roots->right,value);
30    }
31   return roots;
32}
33int max_element_bst(node* roots)
34{
35
36    if(roots==NULL)
37    {
38        return -1;
39    }
40    if(roots->right==NULL)
41    {
42        return roots->data;
43    }
44    else
45    {
46        return max_element_bst(roots->right);
47    }
48}
49int main()
50{
51    node* root=new node;
52    root=NULL;
53    int value;
54    do
55    {
56        cin>>value;
57        if(value>0)
58        {
59            root=insert_bst(root,value);
60        }
61    }while(value>0);
62    cout<<"Maximum element is "<<max_element_bst(root)<<endl;
63}
64