Skip to content

Commit 27ea0a2

Browse files
authored
Create Largest BST
1 parent de49311 commit 27ea0a2

File tree

1 file changed

+70
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 15 - BST II

1 file changed

+70
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
Given a Binary tree, find the largest BST subtree. That is, you need to find the BST with maximum height in the given binary tree. You have to return the height of largest BST.
3+
4+
Input format :
5+
The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node.
6+
7+
Output format:
8+
The first and only line of output contains the height of the largest BST.
9+
10+
Constraints:
11+
Time Limit: 1 second
12+
13+
Sample Input 1:
14+
5 10 6 2 3 -1 -1 -1 -1 -1 9 -1 -1
15+
Sample Output 1:
16+
2
17+
*/
18+
public class Solution {
19+
/*
20+
* BinaryTreeNode class
21+
*
22+
* class BinaryTreeNode<T>
23+
* {
24+
* T data;
25+
* BinaryTreeNode<T> left;
26+
* BinaryTreeNode<T> right;
27+
* public BinaryTreeNode(T data)
28+
* {
29+
* this.data = data;
30+
* }
31+
* }
32+
*/
33+
34+
public static int largestBSTSubtree(BinaryTreeNode<Integer> root) {
35+
// Write your code here
36+
if (root==null)
37+
return 0;
38+
39+
if (isBST(root,Integer.MIN_VALUE,Integer.MAX_VALUE))
40+
return findHeight(root);
41+
else
42+
{
43+
return Math.max(largestBSTSubtree(root.left),largestBSTSubtree(root.right));
44+
}
45+
46+
}
47+
48+
private static int findHeight(BinaryTreeNode<Integer> root)
49+
{
50+
if (root==null)
51+
return 0;
52+
53+
if (root.left==null && root.right==null)
54+
return 1;
55+
56+
return Math.max(findHeight(root.left),findHeight(root.right))+1;
57+
}
58+
59+
private static boolean isBST(BinaryTreeNode<Integer> root, int min, int max)
60+
{
61+
if(root == null)
62+
return true;
63+
64+
if(root.data < min || root.data > max)
65+
return false;
66+
else
67+
return isBST(root.left,min,root.data -1) && isBST(root.right,root.data +1,max);
68+
}
69+
70+
}

0 commit comments

Comments
 (0)