C++ program to find largest number in binary search tree which is less than or equal to N














































C++ program to find largest number in binary search tree which is less than or equal to N



Code:
#include<iostream>
using namespace std;
//class Tree
template<class X>
class Tree
{
    //structure represent the node of BST
    private:
        struct Node
        {
            X data;
            Node *right, *left;
        };
        int max;
    public:

        Node *root;//root node of BST;
        //Method to create a new node of BST
        Node* newNode(X data)
        {
            Node *temp=new Node;
            temp->data=data;
            temp->right=temp->left=NULL;
            return temp;
        }
        //Method to find largest number, less than n in BST
        //it will return zero if tree does not exist or BST dose not contain the element less than n
        int findLargest(Node *root, int n)
        {
            //Base case
            if(root==NULL)
                return max;
            //element found and equal to n
            if(n==root->data)
                return n;
            //search in right subtree
            //n is greater than root data
            if(n>root->data)
            {
                max=root->data;
                findLargest(root->right,n);
            }
            else
                findLargest(root->left,n);//search in left subtree
        }
        //constructor
        Tree()
        {
            max=0;
            root=NULL;
        }

};
//Driver method
int main()
{
    int n=21;
    Tree<int>t1;
    t1.root=t1.newNode(15);
    t1.root->left=t1.newNode(10);
    t1.root->left->left=t1.newNode(8);
    t1.root->left->right=t1.newNode(12);
    t1.root->right=t1.newNode(22);
    t1.root->right->left=t1.newNode(20);
    t1.root->right->right=t1.newNode(24);
    cout<<"Largest Number is "<<t1.findLargest(t1.root,n);
    return 0;
}
Output:
Largest Number is 20

Comments