修改了楼上题解的辅助方法check

import java.util.*;
class TreeNode{
    int val;
    TreeNode left=null,right=null;
    TreeNode(int val){ this.val=val;}
}
public class Main{
    public static void main(String[] args){
        Map<Integer,TreeNode> map=new HashMap<Integer,TreeNode>(){{put(-1,null);}};//存储值与节点对应关系,方便根据值拿出节点
        Scanner sc=new Scanner(System.in);
        int rootVal=sc.nextInt();sc.nextLine();//吸收nextInt()产生的换行符
        map.put(rootVal,new TreeNode(rootVal));
        while(sc.hasNext()){
            String[] str1=sc.nextLine().split(":");
            String[] str2=str1[1].split("[|]");
            int l=Integer.valueOf(str2[0]), r=Integer.valueOf(str2[1]);
            if(l!=-1) map.put(l,new TreeNode(l)); 
            if(r!=-1) map.put(r,new TreeNode(r));
            map.get(Integer.valueOf(str1[0])).left=map.get(l);
            map.get(Integer.valueOf(str1[0])).right=map.get(r);               
        }
        if(check(map.get(rootVal),rootVal)) System.out.println("1");
        else System.out.println("0");
    }
    public static boolean check(TreeNode root,int val){
        if(root==null) return true;
        boolean l=true,r=true;
        if(root.left!=null)
            if(val<=root.left.val||!check(root.left,root.left.val)) l=false;
        if(root.right!=null)
            if(val>=root.right.val||!check(root.right,root.right.val)) r=false;
        if(l&&r) return true;
        return false;
    }
}