98. Verify binary search tree
Given a binary tree to determine if it is a valid binary search tree.
Suppose a binary search tree having the following characteristics:
Left child node of the tree contains only less than the current node number.
Right subtree contain only greater than the number of nodes of the current node.
All left subtree and right subtree itself must also be binary search tree.
Example 1:
Input:
2
/ \
1 3
Output: true
Example 2:
Input:
5
/ \
1 4
/ \
3 6
Output: false
interpretation: Input as: [5,1,4, null, null, 3,6].
5 is a root node, but it is the right child node 4.
class Solution {
double last = -Double.MAX_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
if (isValidBST(root.left)) {
if (last < root.val) {
last = root.val;
return isValidBST(root.right);
}
}
return false;
}
}