首页 > 试题广场 >

判断二叉搜索树

[编程题]判断二叉搜索树
  • 热度指数:18899 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
判断给出的二叉树是否是一个二叉搜索树(BST)
二叉搜索的定义如下
  • 一个节点的左子树上节点的值都小于自身的节点值
  • 一个节点的右子树上的值都大于自身的节点值
  • 所有节点的左右子树都必须是二叉搜索树
如果你不清楚“{1,#,2,3}"的含义的话,请继续阅读
我们用如下方法将二叉树序列化:
二叉树的序列化遵循层序遍历的原则,”#“代表该位置是一条路径的终结,下面不再存在结点。
例如:
    1
   / \
  2   3
     /
    4
     \
      5
上述的二叉树序列化的结果是:"{1,2,3,#,#,4,#,#,5}".
示例1

输入

{1,1}

输出

false
示例2

输入

{0,#,1}

输出

true

说明:本题目包含复杂数据结构TreeNode,点此查看相关信息
import java.util.*;


public class Solution {
    class Info{
        boolean isBST;
        int min;
        int max;
        Info(boolean isBst, int min, int max){
            this.isBST = isBst;
            this.min = min;
            this.max = max;
        }
    }
    public boolean isValidBST (TreeNode root) {
        // write code here
        if(root == null)
            return true;
        return process(root).isBST;
    }
    public Info process(TreeNode head){
        if(head == null)
            return null;
        Info leftInfo = process(head.left);
        Info rightInfo = process(head.right);
        
        int min = head.val;
        int max = head.val;
        
        if(leftInfo != null){
            min = Math.min(min, leftInfo.min);
            max = Math.max(max, leftInfo.max);
        }
        if(rightInfo != null){
            min = Math.min(min, rightInfo.min);
            max = Math.max(max, rightInfo.max);
        }
        
        boolean isBST = false;
        if(
            (leftInfo == null ? true : leftInfo.isBST )
            && 
            (rightInfo == null ? true : rightInfo.isBST)
            &&
            (leftInfo == null ? true : leftInfo.max < head.val)
            && 
            (rightInfo == null ? true : rightInfo.min > head.val)
        )
            isBST = true;
        
        return new Info(isBST, min, max);
    }
}

发表于 2021-09-03 20:41:07 回复(0)
public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
    public boolean isValidBST (TreeNode root) {
        // write code here
        if(root==null)
            return true;
        if(root.left!=null&&root.left.val>=root.val)
             return false;
        if(root.right!=null&&root.val>=root.right.val)
            return false;
        return isValidBST(root.left)&&isValidBST(root.right);
    }
}

发表于 2021-01-03 10:06:52 回复(0)
利用搜索二叉树中序遍历结果递增的性质,递归逐个比较:
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode pre=null;
    boolean flag=true;
    public boolean isValidBST(TreeNode root) {
        if(root==null)
            return true;
        inorder(root);
        return flag;
    }
    public void inorder(TreeNode root){
        if(root!=null){
            inorder(root.left);
            if(pre!=null&&pre.val>=root.val)
                flag=false;
            pre=root;
            inorder(root.right);
        }
    }
}


编辑于 2020-03-11 18:32:04 回复(0)
public class Solution {

    class ReturnType {
        int max;
        int min;
        boolean isBST;
        public ReturnType(int max, int min, boolean isBST) {
            this.max = max;
            this.min = min;
            this.isBST = isBST;
        }
    }

    public boolean isValidBST(TreeNode root) {
        return process(root).isBST;
    }

    public ReturnType process(TreeNode x) {
        if (x == null) {
            return new ReturnType(Integer.MIN_VALUE, Integer.MAX_VALUE, true);
        }
        ReturnType leftData = process(x.left);
        ReturnType rightData = process(x.right);
        int max = Math.max(Math.max(leftData.max, rightData.max), x.val);
        int min = Math.min(Math.min(leftData.min, rightData.min), x.val);
        boolean isBST = leftData.isBST && rightData.isBST && x.val < rightData.min && x.val > leftData.max;
        return new ReturnType(max, min, isBST);
    }
}
发表于 2019-11-10 09:54:04 回复(0)
    int a=-1;
    Stack<TreeNode> stack=new Stack<>();
    TreeNode node=root;
    while (!stack.isEmpty()||node!=null){
        while (node!=null){
            stack.add(node);
            node=node.left;
        }
        if (!stack.isEmpty()){
            node= stack.pop();
            if (a!=-1&&a>=node.val)
                return false;
            a=node.val;
            node=node.right;
        }
    }
    return true;
发表于 2019-07-20 21:49:06 回复(0)

java代码

一开始遍历到一个数组中,然后判断这个数组是否等于它的排序数组,但发现题目中要求二叉树必须是严格递增的,也就是说[1, 1]不是一棵bst。所以只能一个一个的元素遍历判断了:

public class Solution {
    private ArrayList<Integer> vals = new ArrayList<>();

    public boolean isValidBST(TreeNode root) {
        midTraversal(root);
//        ArrayList<Integer> clone = Collections.sort((ArrayList<Integer>) vals.clone();
        for(int i = 0; i < vals.size() - 1; i++){
            if(vals.get(i) >= vals.get(i + 1))
                return false;
        }
        return true;
    }

    private void midTraversal(TreeNode root) {
        if (root == null)
            return;
        midTraversal(root.left);
        vals.add(root.val);
        midTraversal(root.right);
    }
}
发表于 2018-07-18 13:36:26 回复(0)
public class Solution {
    TreeNode preNode = new TreeNode(Integer.MIN_VALUE);
    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        boolean left = isValidBST(root.left);
        boolean cur = (root.val > preNode.val);
        preNode = root;
        boolean right = isValidBST(root.right);
        return left && cur && right;
    }
}
public class Solution {
    TreeNode preNode = new TreeNode(Integer.MIN_VALUE);
    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        if (!isValidBST(root.left)) 
            return false;
        if (root.val <= preNode.val)
            return false;
        preNode = root;
        return isValidBST(root.right);

    }
}
编辑于 2018-03-17 14:35:42 回复(0)
//中序遍历,用一个flag标记顺序是否正确
    boolean flag = true;    
    TreeNode prenode;
    public boolean isValidBST(TreeNode root) {
        inorder(root);
        return flag;
    }

    public void inorder(TreeNode root){
        if(root == null) return;
        inorder(root.left);
        if(prenode != null){
            if(prenode.val >= root.val){
                flag = false;
            }
        }
        prenode = root;
        inorder(root.right);
    }

发表于 2017-08-22 11:09:34 回复(0)
//方法1:每个结点都对应一个上限,一个下限。
public boolean isValidBST(TreeNode root) {
    return isValidRoot(root,Integer.MIN_VALUE,Integer.MAX_VALUE);
}
public boolean isValidRoot(TreeNode root,int lower,int upper){
    if(root==null) return true;
    if(root.val<=lower || root.val>=upper) return false;
    return isValidRoot(root.left,lower,root.val)
            && isValidRoot(root.right,root.val,upper);
}
//方法2:中序遍历,记录前一个结点,与当前结点的值比较。
public class Solution {
    TreeNode pre;
    boolean isValidBST=true;
    public boolean isValidBST(TreeNode root) {
        inTraversal(root);
        return isValidBST;
    }
    public void inTraversal (TreeNode root){
        if(root==null) return ;
        inTraversal(root.left);
        if(pre!=null&&pre.val>=root.val) isValidBST=false;
        pre=root;
        inTraversal(root.right);
    }
}

编辑于 2017-05-03 14:52:45 回复(3)
public class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;

        boolean judge = true;
        TreeNode leftMaxNode;
        TreeNode rightMinNode;
        if (root.left != null) {
            leftMaxNode = root.left;
            while (leftMaxNode.right != null) {
                leftMaxNode = leftMaxNode.right;
            }
            judge = judge && (leftMaxNode.val < root.val);
        }
        if (root.right != null) {
            rightMinNode = root.right;
            while (rightMinNode.left != null) {
                rightMinNode = rightMinNode.left;
            }
            judge = judge && (rightMinNode.val > root.val);
        }

        return judge && isValidBST(root.left) && isValidBST(root.right);

    }
}
编辑于 2017-04-27 22:33:03 回复(0)
import java.util.*;
public class Solution {
    public boolean isValidBST(TreeNode root) {
		List<TreeNode> list = new ArrayList<>();
		inorder(root, list);
		for (int i = 1; i < list.size(); i ++) {
			if(list.get(i).val <= list.get(i - 1).val) return false;
		}
		return true;
	}
	public static void inorder(TreeNode root, List<TreeNode> list) {
		if(root != null) {
			inorder(root.left, list);
			list.add(root);
			inorder(root.right, list);
		}
	}
}

发表于 2017-04-15 15:24:33 回复(1)
public class Solution { public boolean isValidBST(TreeNode root) { return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    } public boolean isValidBST(TreeNode root, long minVal, long maxVal) { if (root == null) return true; if (root.val >= maxVal || root.val <= minVal) return false; return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
    }
}

发表于 2017-03-12 11:12:27 回复(0)