用上下界去判断二叉搜索树
import java.util.*; class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode(int val){ this.val=val; this.left=null; this.right=null; } }; public class Main{ public static void main(String []args){ int n=0,r1=0; Scanner input=new Scanner(System.in); n=input.nextInt(); r1=input.nextInt(); TreeNode root; TreeNode[]tree =new TreeNode[n+1]; for(int i=0;i<=n;i++){ tree[i]=new TreeNode(1); } for (int i=1;i<=n;i++) { int v,l,r; v=input.nextInt(); l=input.nextInt(); r=input.nextInt(); tree[i].val = v; tree[i].left=(l==0?null:tree[l]); tree[i].right=(r==0?null:tree[r]); } root=tree[r1]; Main main=new Main(); int low=Integer.MIN_VALUE; int high=Integer.MAX_VALUE; boolean res=main.isBinarySearchTree(root,low,high); if(res){ System.out.println("true"); return; } System.out.println("false"); return; } boolean isBinarySearchTree(TreeNode root,int lowBaund,int highBaund) { if(root==null){ return true; } int val=root.val; if(val<=lowBaund||val>=highBaund){ return false; } boolean left=isBinarySearchTree(root.left,lowBaund,val); boolean right=isBinarySearchTree(root.right,val,highBaund); return left&&right; } }