有一半的代码都在处理输入格式:
import java.util.*; class TreeNode{ //定义树节点 int val; TreeNode left, right; TreeNode(int n){val = n;} } public class Main { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); Map<Integer, TreeNode> m = new HashMap<>(); //用节点值映射树节点 m.put(-1, null); int r = Integer.parseInt(sc.nextLine()); //根节点 m.put(r, new TreeNode(r)); while(sc.hasNextLine()){ String[] v1 = sc.nextLine().split(":"); //处理这奇葩的输入 String[] v2 = v1[1].split("[|]"); int lf = Integer.parseInt(v2[0]), rt = Integer.parseInt(v2[1]); if(lf != -1) m.put(lf, new TreeNode(lf)); if(rt != -1) m.put(rt, new TreeNode(rt)); m.get(Integer.parseInt(v1[0])).left = m.get(lf); m.get(Integer.parseInt(v1[0])).right = m.get(rt); } if(h(m.get(r))) System.out.println(1); else System.out.println(0); } static int f(TreeNode r){ //求一棵树的最大节点值 if(r == null) return Integer.MIN_VALUE; return Math.max(Math.max(f(r.left), f(r.right)), r.val); } static int g(TreeNode r){ //求一棵树的最小节点值 if(r == null) return Integer.MAX_VALUE; return Math.min(Math.min(g(r.left), g(r.right)), r.val); } static boolean h(TreeNode r){ //判断BST if(r == null) return true; return r.val > f(r.left) && r.val < g(r.right) && h(r.left) && h(r.right); } }