/* * 255.Verify Preorder Sequence in Binary Search Tree * Given an array of numbers, * verify whether it is the correct preorder traversal sequence of a binary * search tree. * 11.21 By Mingyang * Time complexity O(n^2), space complexity O(1). */ public boolean verifyPreorder(int[] preorder) { if (preorder == null || preorder.length <= 1) { return true; } return dfs(preorder, 0, preorder.length - 1); } private boolean dfs(int[] preorder, int low, int hi) { if (low >= hi) { return true; } int root = preorder[low]; int i = low + 1; while (i <= hi && preorder[i] < root) { i++; } int j = i; while (j <= hi && preorder[j] > root) { j++; } if (j <= hi) { return false; } return dfs(preorder, low + 1, i - 1) && dfs(preorder, i, hi); }
/* * 自己的代码,写的几乎一模一样,很高兴! * 唯一没想到的就是if (start >= end)都应该返回true * 因为2,3两个数的情况时,最后一个return的返回,第一个就是start>end的情况,这应该返回true */ public static boolean verifyPreorder(int[] preorder) { int len = preorder.length; if (preorder == null || len == 0) return true; return verifyHelper(preorder, 0, len - 1); } public static boolean verifyHelper(int[] preorder, int start, int end) { if (start >= end) return true; int val = preorder[start]; int index = -1; for (int i = start + 1; i <= end; i++) { if (preorder[i] > val && index == -1) { index = i; } if (preorder[i] < val && index != -1) return false; } if (index != -1) return verifyHelper(preorder, start + 1, end); return verifyHelper(preorder, start + 1, index - 1) && verifyHelper(preorder, index, end); }