Validate binary search tree
BST 是左樹最大值比根小,右樹最小值比根大,推及至所有的子樹
因此一開始想到是需要用額外的 class Result,來記錄現在是左樹還是右樹,然後左樹紀錄最大值,右樹記錄最小值
不過 isLeft 這種參數就很尷尬,不知道該怎麼在遞迴時擺進去?
癥結點其實是在我想要紀錄左樹最大值,那其實可以用 Math.max(left.max, root.val)
即可,因為右邊一定比左和根大!
因此可以寫成這樣:
class Result {
boolean isBST;
int min;
int max;
public Result(boolean b, int _min, int _max) {
isBST = b;
min = _min;
max = _max;
}
}
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
return helper(root).isBST;
}
public Result helper(TreeNode root) {
if (root == null) {
return new Result(true, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
Result left = helper(root.left);
Result right = helper(root.right);
//exclude all false case
if (!left.isBST || !right.isBST) {
return new Result(false, 0, 0);
}
if (root.left != null && left.max >= root.val ||
root.right != null && right.min <= root.val) {
return new Result(false, 0, 0);
}
return new Result(true,
Math.min(left.min, root.val),
Math.max(right.max, root.val));
}