Largest binary search tree (BST) in a binary tree

Given a binary tree, find the largest Binary Search Tree (BST), where largest means BST with largest number of nodes in it. The largest BST may or may not include all of its descendants.

Sponsored: has published a chatbot, who can chat with you and help you find apartments in San Francisco and Bay area. Check it out:

01 int LBST(Node* head, int min, int max, Node*& max_hd, int& cnt)
02 {
03     if(head==NULL)
04         return 0;
05     int cur_cnt=0;
06     if((head->value<=max)&&(head->value>=min)){
07         int left_cnt=LBST(head->left,min,head->value, max_hd, cnt);
08         int right_cnt=LBST(head->right,head->value,max,max_hd,cnt);
09         cur_cnt=left_cnt+right_cnt+1;
10         if(cur_cnt>cnt){
11             cnt=cur_cnt;
12             max_hd=head;
13         }
14     }
15     LBST(head->left,MIN,MAX, max_hd,cnt);
16     LBST(head->right,MIN,MAX,max_hd,cnt);
17     return cur_cnt;
18 }
This entry was posted in Binary search, Recursive, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s