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點(diǎn)性質(zhì)甚垦,一般bst的遍歷敌蚜,都需要保存一個interval盟榴,保證該bst子樹的所有node的值都在interval范圍內(nèi)W狻o醯骸!
代碼:
/**
* 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);
}
}