|
| 1 | +package class07; |
| 2 | + |
| 3 | +public class Code06_IsBinarySearchTree { |
| 4 | + |
| 5 | + public static class TreeNode { |
| 6 | + public int val; |
| 7 | + public TreeNode left; |
| 8 | + public TreeNode right; |
| 9 | + |
| 10 | + TreeNode(int val) { |
| 11 | + this.val = val; |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + public static class Info { |
| 16 | + public boolean isBST; |
| 17 | + public int max; |
| 18 | + public int min; |
| 19 | + |
| 20 | + public Info(boolean is, int ma, int mi) { |
| 21 | + isBST = is; |
| 22 | + max = ma; |
| 23 | + min = mi; |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | +// public static Info process(TreeNode x) { |
| 28 | +// if (x == null) { |
| 29 | +// return null; |
| 30 | +// } |
| 31 | +// Info leftInfo = process(x.left); |
| 32 | +// Info rightInfo = process(x.right); |
| 33 | +// int max = x.val; |
| 34 | +// int min = x.val; |
| 35 | +// if (leftInfo != null) { |
| 36 | +// max = Math.max(leftInfo.max, max); |
| 37 | +// min = Math.min(leftInfo.min, min); |
| 38 | +// } |
| 39 | +// if (rightInfo != null) { |
| 40 | +// max = Math.max(rightInfo.max, max); |
| 41 | +// min = Math.min(rightInfo.min, min); |
| 42 | +// } |
| 43 | +// boolean isBST = true; |
| 44 | +// if (leftInfo != null && !leftInfo.isBST) { |
| 45 | +// isBST = false; |
| 46 | +// } |
| 47 | +// if (rightInfo != null && !rightInfo.isBST) { |
| 48 | +// isBST = false; |
| 49 | +// } |
| 50 | +// boolean leftMaxLessX = leftInfo == null ? true : (leftInfo.max < x.val); |
| 51 | +// boolean rightMinMoreX = rightInfo == null ? true : (rightInfo.min > x.val); |
| 52 | +// if (!(leftMaxLessX && rightMinMoreX)) { |
| 53 | +// isBST = false; |
| 54 | +// } |
| 55 | +// return new Info(isBST, max, min); |
| 56 | +// } |
| 57 | + |
| 58 | + public static Info process(TreeNode x) { |
| 59 | + if (x == null) { |
| 60 | + return null; |
| 61 | + } |
| 62 | + Info leftInfo = process(x.left); |
| 63 | + Info rightInfo = process(x.right); |
| 64 | + int max = x.val; |
| 65 | + int min = x.val; |
| 66 | + if (leftInfo != null) { |
| 67 | + max = Math.max(leftInfo.max, max); |
| 68 | + min = Math.min(leftInfo.min, min); |
| 69 | + } |
| 70 | + if (rightInfo != null) { |
| 71 | + max = Math.max(rightInfo.max, max); |
| 72 | + min = Math.min(rightInfo.min, min); |
| 73 | + } |
| 74 | + boolean isBST = false; |
| 75 | + boolean leftIsBst = leftInfo == null ? true : leftInfo.isBST; |
| 76 | + boolean rightIsBst = rightInfo == null ? true : rightInfo.isBST; |
| 77 | + boolean leftMaxLessX = leftInfo == null ? true : (leftInfo.max < x.val); |
| 78 | + boolean rightMinMoreX = rightInfo == null ? true : (rightInfo.min > x.val); |
| 79 | + if (leftIsBst && rightIsBst && leftMaxLessX && rightMinMoreX) { |
| 80 | + isBST = true; |
| 81 | + } |
| 82 | + return new Info(isBST, max, min); |
| 83 | + } |
| 84 | + |
| 85 | +} |
0 commit comments