LeetCode098——验证二叉搜索树
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/validate-binary-search-tree/description/
题目描述:
知识点:二叉搜索树、递归
思路一:递归判断
递归终止条件:
如果root节点为null或者root的左右节点均为null,我们直接返回true。
递归过程:
(1)如果root的左节点为null且右节点不为null。
如果此时root的值小于右子树中的最小值且root的右子树是一棵二分搜索树,返回true。否则,返回false。
(2)如果root的左节点不为null且右节点为null。
如果此时root的值大于左子树中的最大值且root的左子树是一棵二分搜索树,返回true。否则,返回false。
(3)如果root的左右节点均不为null。
如果此时root的值大于左子树中的最大值且小于右子树中的最小值且root的左右子树均是一棵二分搜索树,返回true。否则,返回false。
时间复杂度是O(n),其中n为树中的节点个数。空间复杂度即递归深度,是O(h),其中h为树的高度。
JAVA代码:
public class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null ||(root.left == null && root.right == null)){
return true;
}
if(root.left == null && root.right != null){
if(root.val < findMinTreeNode(root.right) && isValidBST(root.right)){
return true;
}
}else if(root.left != null && root.right == null){
if(root.val > findMaxTreeNode(root.left) && isValidBST(root.left)){
return true;
}
}else if(root.left != null && root.right != null){
if(root.val < findMinTreeNode(root.right) && root.val > findMaxTreeNode(root.left) && isValidBST(root.left) && isValidBST(root.right)){
return true;
}
}
return false;
}
private int findMinTreeNode(TreeNode root){
while(root.left != null){
root = root.left;
}
return root.val;
}
private int findMaxTreeNode(TreeNode root){
while(root.right != null){
root = root.right;
}
return root.val;
}
}
LeetCode解题报告:
思路二:中序遍历
对于一棵二分搜索树而言,其中序遍历的结果是一个递增序列。这里我采用的是递归的形式实现中序遍历,更多中序遍历算法请见LeetCode094——二叉树的中序遍历。
时间复杂度是O(n),其中n为树中的节点个数。空间复杂度也是O(n)。
JAVA代码:
public class Solution {
List<Integer> list;
public boolean isValidBST(TreeNode root) {
list = new ArrayList<>();
inorderTraversal(root);
for(int i = 1; i < list.size(); i++){
if(list.get(i) <= list.get(i - 1)){
return false;
}
}
return true;
}
private void inorderTraversal(TreeNode root){
if(root == null){
return;
}
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
}
}
LeetCode解题报告:
思路三:思路二的改进
思路二把中序遍历的结果都保存在了一个List集合里,在遍历完成之后判断集合中的元素是否按递增顺序排列。事实上,我们完全可以在中序遍历的过程中就对结果进行验证。这里我采用的是递归的形式实现中序遍历,更多中序遍历算法请见LeetCode094——二叉树的中序遍历。
时间复杂度是O(n),其中n为树中的节点个数。空间复杂度即递归深度,是O(h),其中h为树的高度。
JAVA代码:
public class Solution {
Integer pre = null;
public boolean isValidBST(TreeNode root) {
return inorderTraversal(root);
}
private boolean inorderTraversal(TreeNode root){
if(root == null){
return true;
}
if(!inorderTraversal(root.left)){
return false;
}
if(pre != null && root.val <= pre){
return false;
}
pre = root.val;
if(!inorderTraversal(root.right)){
return false;
}
return true;
}
}
LeetCode解题报告: