Prompt
Write a function that takes in a potentially invalid Binary Search Tree (BST) and returns a boolean representing whether the BST is valid.
Each BST node has an integer value , a left child node, and a right child node. A node is said to be a valid BST node if and only if it satises the BST property: its value is strictly greater than the values of every node to its left; its value is less than or equal to the values of every node to its right; and its children nodes are either valid BST nodes themselves or None / null .
A BST is valid if and only if all of its nodes are valid BST nodes.
Sample Input
Sample Output
true
Solution
import java.util.*;
class Program {
// O(n) time | O(d) space
public static boolean validateBst(BST tree) {
// Write your code here.
return validateBST(tree, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
public static boolean validateBST(BST tree, int maxValue, int minValue) {
if(tree.value >= maxValue || tree.value < minValue) {
return false;
}
if (tree.left != null && !validateBST(tree.left, tree.value, minValue)) {// A
return false;
}
if(tree.right != null && !validateBST(tree.right, maxValue, tree.value)) {
return false ;
}
return true;//B
// if(tree.right != null) {
// return validateBST(tree.right, maxValue, tree.value);
// }
// return true;
}
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
}
}
# 1A
return后,要考虑接受return的值,这是一种接受return值的方式
# 1B
如果没有三个if的情况,就一直pass,直到return tree
Solution 2
import java.util.*;
class Program {
// O(n) time | O(d) space
public static boolean validateBst(BST tree) {
// Write your code here.
return validateBST(tree, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
public static boolean validateBST(BST tree, int maxValue, int minValue) {
if (tree == null) {//A
return true;
}
if(tree.value >= maxValue || tree.value < minValue) {
return false;
}
return validateBST(tree.left, tree.value, minValue) && validateBST(tree.right, maxValue, tree.value);//B
}
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
}
}
# 1B
base case
# 2B
细品