10
/ \
5 15
/ \ \
1 8 7
return 3
public class Solution {
public int largestBSTSubtree(TreeNode root) {
if(root == null) return 0;
int[] res = recursive(root);
return res[2];
}
public int[] recursive(TreeNode root){
int[] res = new int[5];
// res[0] BST or Not?
// res[1] total number nodes of subtree
// res[2] max number of BST subtree
// res[3] min
// res[4] max
res[0] = 1; res[3] = Integer.MAX_VALUE; res[4] = Integer.MIN_VALUE;
if(root == null) return res;
int[] resL = recursive(root.left);
int[] resR = recursive(root.right);
if(resL[0] == 0 || resR[0] == 0 || resL[4] >= root.val || resR[3] <= root.val)
res[0] = 0;
res[1] = resL[1] + resR[1] + 1;
res[2] = (res[0] == 1) ? res[1]: Math.max(resL[2], resR[2]);
res[3] = root.val < resL[3] ? root.val : resL[3];
res[4] = root.val > resR[4] ? root.val : resR[4];
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。