Largest BST Subtree
Last updated
Last updated
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
private int[] helper(TreeNode root) {
int[] res = new int[3]; // res, min, max
if (root == null) {
return res;
}
int[] left = helper(root.left);
int[] right = helper(root.right);
if (left[0] == -1 || right[0] == -1 || left[0] != 0 && root.val <= left[2] || right[0] != 0 && root.val >= right[1]) {
res[0] = -1;
return res;
}
res[0] = left[0] + right[0] + 1;
max = Math.max(max, res[0]);
res[1] = left[0] == 0 ? root.val : left[1];
res[2] = right[0] == 0 ? root.val : right[2];
return res;
}
public int largestBSTSubtree(TreeNode root) {
helper(root);
return max;
}
}