98. Validate Binary Search Tree
by Botao Xiao
Question:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- Both the left and right subtrees must also be binary search trees.
Example 1:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
Thinking:
- Method:
- 递归遍历,要确定是否为valid则要确定当前节点的值是否在范围之间。
- 范围初始化值为Long.MAX_VALUE和Long.MIN_VALUE
- 对于左子树而言,上限就是当前的结点。
- 对于右子树而言,下限就是当前的结点。
- 遍历到null(叶子结点),则说明为true,这也是退出递归的条件。
- 递归遍历,要确定是否为valid则要确定当前节点的值是否在范围之间。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return check(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private static boolean check(TreeNode node, long min, long max){
if(node == null) return true;
if(node.val >= max || node.val <= min) return false;
return check(node.left, min, node.val) && check(node.right, node.val, max);
}
}
二刷
这道题写出来还是很快的,对于这种树的判断,大多是使用递归的方法。但是初始的最大值和最小值我还是用Integer类型的,所以会有Error。以后要将这样的情况考虑进来。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return check(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean check(TreeNode node, long min, long max){
if(node == null) return true;
if(node.val <= min || node.val >= max) return false;
return check(node.left, min, node.val) && check(node.right, node.val, max);
}
}
Subscribe via RSS