Largest sub-tree which is a binary search tree (BST)

Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.

C++:
01 int LBSTsubtree(Node* head, int min, int max, Node*& max_hd, int& cnt)
02 {
03     if(head==NULL)
04         return 0;
05     LBSTsubtree(head->left,MIN,MAX, max_hd,cnt);
06     LBSTsubtree(head->right,MIN,MAX,max_hd,cnt);
07     if((head->value<=max)&&(head->value>=min)){
08         int left_cnt=
09             LBSTsubtree(head->left,min,head->value,max_hd,cnt);
10         int right_cnt=
11             LBSTsubtree(head->right,head->value,max,max_hd,cnt);
12         if((left_cnt<0)||(right_cnt<0))
13             return 1;
14         int cur_cnt=left_cnt+right_cnt+1;
15         if(cur_cnt>cnt){
16             cnt=cur_cnt;
17             max_hd=head;
18         }
19         return cur_cnt;
20     }
21     return 1;
22 }
Advertisements
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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s