Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created April 21, 2016 00:32
Show Gist options
  • Save cangoal/207a8cb4f848e94073849f43ce65798d to your computer and use it in GitHub Desktop.
Save cangoal/207a8cb4f848e94073849f43ce65798d to your computer and use it in GitHub Desktop.
LeetCode - Largest BST Subtree
// 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.
// Note:
// A subtree must include all of its descendants.
// Here's an example:
// 10
// / \
// 5 15
// / \ \
// 1 8 7
// The Largest BST Subtree in this case is the highlighted one.
// The return value is the subtree's size, which is 3.
int max = 0;
public int largestBSTSubtree(TreeNode root) {
helper(root);
return max;
}
private int[] helper(TreeNode root){
int[] res = new int[]{0, Integer.MAX_VALUE, Integer.MIN_VALUE};
if(root == null) return res;
int[] left = helper(root.left);
int[] right = helper(root.right);
if(left[0] == -1 || right[0] == -1 || root.val <= left[2] || root.val >= right[1]){
res[0] = -1; res[1] = 0; res[2] = 0;
return res;
}
res[0] = left[0] + 1 + right[0];
max = Math.max(res[0], max);
res[1] = Math.min(left[1], root.val);
res[2] = Math.max(right[2], root.val);
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment