import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] seq = new int[n]; String[] str = br.readLine().split(" "); for(int i = 0; i < n; i++) seq[i] = Integer.parseInt(str[i]); int leftNums = seq[seq.length - 1]; leftNums --; // 左子树节点数 System.out.println(isBST(leftNums, seq)); } private static boolean isBST(int leftNums, int[] seq) { if(leftNums <= 0 || seq.length == 1) return true; // 只有一个节点或没有左子树了直接返回true int rootVal = seq[seq.length - 1]; // 当前子树根节点值 // 左子树有比根节点值大的节点就返回false for(int i = 0; i < leftNums; i++) if(seq[i] >= rootVal) return false; // 右子树有比根节点小的节点也返回false for(int i = leftNums; i < seq.length - 1; i++) if(seq[i] <= rootVal) return false; int[] leftTree = Arrays.copyOfRange(seq, 0, leftNums); int[] rightTree = Arrays.copyOfRange(seq, leftNums, seq.length - 1); // 左右子树都要是BST return isBST(getLeftNums(leftTree), leftTree) && isBST(getLeftNums(rightTree), rightTree); } // 计算比根节点小的节点数 private static int getLeftNums(int[] nums) { int count = 0; for(int i = 0; i < nums.length - 1; i++) if(nums[i] < nums[nums.length - 1]) count ++; return count; } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = in.nextInt(); } System.out.println(isPost(array, 0, array.length - 1)); } /* 0 <= first <= last < array.length */ private static boolean isPost(int[] array, int first, int last) { int less = first - 1; int more = last; for (int i = first; i < last; i++) { if (array[i] < array[last]) { less = i; } else { more = more == last ? i : more; } } return less + 1 == more && (less < first || isPost(array, first, less)) && (more == last || isPost(array, more, last - 1)); } }思路:
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i] = scanner.nextInt(); } System.out.println(isPostOrder(arr, 0, n-1)); } private static boolean isPostOrder(int arr[],int start,int end) { if(start >=end) return true; int rootVal = arr[end]; boolean flag = false; int mid = end; for(int i=start;i<end;i++) { if(!flag && arr[i]>rootVal) { mid = i; flag = true; }else if(flag && arr[i]<rootVal) { return false; } } return isPostOrder(arr, start, mid-1) && isPostOrder(arr, mid, end-1); } }