0
点赞
收藏
分享

微信扫一扫

[LeetCode]Validate Binary Search Tree


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:

2
/ \
1 3

Binary tree ​​[2,1,3]​​​, return true.
Example 2:

1
/ \
2 3

Binary tree ​​[1,2,3]​​, return false.

本题难度Medium。

【复杂度】
时间 O(N) 空间 O(1)

【思路】
实际上就是对每个节点​​​root​​​设定其取值范围​​(min,max)​​​,然后再进行判断;完成本节点判断后,再设定其两个儿子的取值范围,左儿子为​​(min,root.val)​​​,右儿子为​​(root.val,max)​​。

root  (min,max)
/ \
(min,root.val) left right (root.val,max)

【代码】

/**
* 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 check(root,null,null);
}
private boolean check(TreeNode root,TreeNode min,TreeNode max){
//base case
if(root==null)
return true;

if(min!=null&&min.val>=root.val)
return false;
if(max!=null&&max.val<=root.val)
return false;
return (!check(root.left,min,root))?false:check(root.right,root,max);
}
}

【follow up】
我看了有的代码中的​​​min、max​​​设置为int变量,第12行于是便改写为:​​return check(root,Integer.MIN_INT,Integer.MAX_INT);​​代码如下:

public class Solution {
public boolean isValidBST(TreeNode root) {
return check(root,Integer.MIN_INT,Integer.MAX_INT);
}
private boolean check(TreeNode root,int min,int max){
//base case
if(root==null)
return true;

return min<root.val&&root.val<max
&&check(root.left,min,root.val);
&&check(root.right,root.val,max);

}
}

但是这里有个问题:如果某个节点的值就是​​MIN_INT​​​或​​MAX_INT​​呢?按逻辑这是允许的,但是在这里就会被判定为false。


举报

相关推荐

0 条评论