当前节点作为根节点的话,对应的子树是否为BST,需要判断他的左子树的状态和它的右子树的状态,并且数值是否满足大小关系。
所以需要后序遍历。
那么如何记录数字排序的状态呢?通过自己封装一层MyNode,记录所在子树的最大值和最小值。走到每个点的时候,都会判断左子树的最大值,右子树的最小值和当前节点的值进行大小比较。
public class test {
int res = 0;
public int largeestBSTSubTree(TreeNode root){
postorder(new MyNode(root));
return res;
}
private void postorder(MyNode root){
if(root == null){
return;
}
root.size = 1;
MyNode left = null;
MyNode right = null;
if(root.node.left != null){
left = new MyNode(root.node.left, root.node.left.val, root.node.left.val);
}
if(root.node.right != null){
right = new MyNode(root.node.right, root.node.right.val, root.node.right.val);
}
postorder(left);
postorder(right);
boolean lValid = left == null || (left.max < root.node.val && left.size >= 1);
boolean rValid = right == null || (right.min > root.node.val && right.size >= 1);
if(lValid && rValid){
root.size = (left == null ? 0 : left.size) + (right == null ? 0 : right.size) + 1;
if(left != null){
root.min = left.min;
}
if(right != null){
root.max = right.max;
}
}else{
root.size = 0;
}
res = Math.max(root.size, res);
}
}
class MyNode{
TreeNode node;
int max;
int min;
int size;
public MyNode(TreeNode node){
this.node = node;
max = node.val;
min = node.val;
}
public MyNode(TreeNode node, int max, int min){
this.node = node;
this.max = max;
this.min = min;
}
}