LeetCode 98 Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
1 The left subtree of a node contains only nodes with keys less than the node's key.
2 The right subtree of a node contains only nodes with keys greater than the node's key.
3 Both the left and right subtrees must also be binary search trees.
要理解bst的以上3点性质,一般bst的遍历,都需要保存一个interval,保证该bst子树的所有node的值都在interval范围内!!!
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return isValidRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValidRecursive(TreeNode root, long min, long max) {
return root == null ||
root.val < max && root.val > min &&
isValidRecursive(root.left, min, root.val) && isValidRecursive(root.right, root.val, max);
}
}