- 检验的时候,从递归的最底层开始检查起
- 在判断subtree的时候,递归时候考虑用post-order traverse, 这样可以先照顾到左右subtree,进而可以判断root为起点的这个subtree
- subtree是可以只有一个点的(但是这个点必须是leaf),并且是可以包括root,但是不能去掉左边或者右边的分支,如果有subchild一定要被包括在内
- 设立递归方程时候,务必要把思路写清楚,比如这里,递归方程就可以是以root为起点的subtree是否存在
- 子树-> post order
- BST 用size = -1来判定是否是valid bst。同时利用BST的性质,BST的子树都必须是BST
- 最后生成resulttype时候,记得还是要跟root.val比较,是为了更新leaf节点和null节点的值
class ResultType {
public int size;
public int max;
public int min;
public ResultType(int size, int max, int min) {
this.size = size;
this.max = max;
this.min = min;
}
}
int ans;
public int largestBSTSubtree(TreeNode root) {
if (root == null) return 0;
ans = 1;
ResultType result = helper(root);
return ans;
}
private ResultType helper(TreeNode root) {
if (root == null) return new ResultType(0, Integer.MIN_VALUE, Integer.MAX_VALUE);
ResultType left = helper(root.left);
ResultType right = helper(root.right);
if (left.size == -1 || right.size == -1 || left.max >= root.val || root.val >= right.min)
return new ResultType(-1, 0, 0);
int size = left.size + right.size + 1;
ans = Math.max(ans, size);
return new ResultType(size, Math.max(right.max, root.val), Math.min(left.min, root.val));
}