给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
思路:利用二叉搜索树的特性:结点的值,左<中<右,中序遍历出来,得到的是有序的数据。只需判断是否有序即可。
/**
* 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) {
if(root == null){
return true;
}
List<Integer> list = new ArrayList<>();
orderBST(root,list);
for(int i = 0;i < list.size()-1;i++){
if(list.get(i) >= list.get(i+1)){
return false;
}
}
return true;
}
public static void orderBST(TreeNode root,List<Integer> list){
if(root == null ) return;
orderBST(root.left,list);
list.add(root.val);
orderBST(root.right,list);
}
}
思路二:根据二叉树的特性做,左边的结点最大值就是根节点,而右子树的最小值是根节点。
/**
* 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) {
if(root == null) {
return true;
}
return validBSTRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean validBSTRecursive(TreeNode root, long minValue, long maxValue) {
if(root == null) {
return true;
} else if(root.val >= maxValue || root.val <= minValue) {
return false;
} else {
return validBSTRecursive(root.left, minValue, root.val) && validBSTRecursive(root.right, root.val, maxValue);
}
}
}
c 语言:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool fun(struct TreeNode* root,long low,long heigh){
if(root == NULL) return true;
long num = root->val;
if(num <= low || num >= heigh) return false;
return fun(root->left,low,num) && fun(root->right,num,heigh);
}
bool isValidBST(struct TreeNode* root){
return fun(root,LONG_MIN,LONG_MAX);
}