原题网址:https://leetcode.com/problems/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 7The 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?
方法:递归检查。一颗子树当且仅当其左右子树都是BST,并且左子树的最大值小于根节点,右子树的最小值大于根节点的时候,这棵子树才是BST。则定一个递归函数的返回结果,包括该节点能否形成一棵BST,以及该BST的节点总数。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int max = 0;
private Range check(TreeNode root) {
Range range = new Range(root.val, root.val);
Range left = (root.left == null) ? null : check(root.left);
Range right = (root.right == null) ? null: check(root.right);
if (left != null) {
if (!left.bst || left.max >= root.val) return range;
range.min = left.min;
range.count += left.count;
}
if (right != null) {
if (!right.bst || root.val >= right.min) return range;
range.max = right.max;
range.count += right.count;
}
range.bst = true;
max = Math.max(max, range.count);
return range;
}
public int largestBSTSubtree(TreeNode root) {
if (root != null) check(root);
return max;
}
}
class Range {
boolean bst;
int min, max;
int count = 1;
Range(int min, int max) {
this.min = min;
this.max = max;
}
}
另一种实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int max = 0;
private Range find(TreeNode root) {
Range range = new Range(root.val, root.val, 1);
Range left = root.left == null ? null : find(root.left);
Range right = root.right == null ? null : find(root.right);
if (root.left != null) {
if (left == null) return null;
if (left.max >= root.val) return null;
range.min = left.min;
range.nodes += left.nodes;
}
if (root.right != null) {
if (right == null) return null;
if (right.min <= root.val) return null;
range.max = right.max;
range.nodes += right.nodes;
}
max = Math.max(max, range.nodes);
return range;
}
public int largestBSTSubtree(TreeNode root) {
if (root == null) return 0;
find(root);
return max;
}
}
class Range {
int min, max;
int nodes;
Range(int min, int max, int nodes) {
this.min = min;
this.max = max;
this.nodes = nodes;
}
}