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.
Hint:
You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity.
Follow up:
Can you figure out ways to solve it with O(n) time complexity?
Solution
public class Solution {
public int largestBSTSubtree(TreeNode root) {
if (root == null) return 0;
if (isValidBST(root)) return largestBSTSubtree(root.left)+largestBSTSubtree(root.right)+1;
else return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right));
}
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean dfs(TreeNode root, long min, long max) {
if (root == null) return true;
if (root.val <= min || root.val >= max) return false;
return dfs(root.left, min, root.val) && dfs(root.right, root.val, max);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。