333 Largest BST Subtree
333. Largest BST Subtree
1. Question
10
/ \
5 15
/ \ \
1 8 72. Implementation
3. Time & Space Complexity
Last updated
10
/ \
5 15
/ \ \
1 8 7Last updated
class Solution {
public int largestBSTSubtree(TreeNode root) {
int[] maxSize = new int[1];
dfs(root, maxSize);
return maxSize[0];
}
public long[] dfs(TreeNode node, int[] maxSize) {
if (node == null) {
return new long[] {Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
}
long[] left = dfs(node.left, maxSize);
long[] right = dfs(node.right, maxSize);
if (left[2] == -1 || right[2] == -1 || node.val <= left[1] || node.val >= right[0]) {
return new long[] {0, 0, -1};
}
int count = (int)(left[2] + right[2] + 1);
maxSize[0] = Math.max(maxSize[0], count);
return new long[] {Math.min(left[0], node.val), Math.max(right[1], node.val), count};
}
}