leetcode [98]Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄
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:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。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.
题目大意:
查看这个树是否满足二叉搜索树的要求。
解法:
如果满足二叉搜索树,那么这个树的中序遍历一定是升序的,所以利用中序遍历查看序列是否是满足升序条件即可。
java:
class Solution {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode>s=new Stack<TreeNode>();
TreeNode pre=null;
while(!s.empty()||root!=null){
while(root!=null){
s.push(root);
root=root.left;
}
root=s.pop();
if(pre!=null && pre.val >= root.val) return false;
pre=root;
root=root.right;
}
return true;
}
}
还有一种解法,就是递归的判断左右子树是否在给定数值范围内。
java:
class Solution {
public boolean isVaildBSTCore(TreeNode root,long minVal,long maxVal){
if(root==null) return true;
if(minVal>=root.val || maxVal<=root.val) return false;
return isVaildBSTCore(root.left,minVal,root.val)&&isVaildBSTCore(root.right,root.val,maxVal);
}
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
return isVaildBSTCore(root,Long.MIN_VALUE,Long.MAX_VALUE);
}
}
更多精彩

