publicstatic Node process1(int[] posArr, int L, int R){ if (L > R) returnnull; Node head = new Node(posArr[R]); if (L == R) return head; int M = L - 1; // 为了全部是全左或全右子树 for (int i = L; i < R; i++) { if (posArr[i] < posArr[R]) { M = i; } } head.left = process1(posArr, L, M); head.right = process1(posArr, M + 1, R - 1); return head; }
publicstatic Node process2(int[] posArr, int L, int R){ Node head = new Node(posArr[R]); if (L == R) return head; int M = -1; for (int i = L; i < R; i++) { if (posArr[i] < posArr[R]) { M = i; } }
if (M == -1) { head.right = process1(posArr, L, R - 1); } elseif (M == R - 1) { head.left = process2(posArr, L, R - 1) } else { head.left = process1(posArr, L, M); head.right = process1(posArr, M + 1, R - 1); }
return head; }
publicstatic Node process3(int[] posArr, int L, int R){ if (L > R) returnnull; Node head = new Node(posArr[R]); if (L == R) return head; int M = L - 1; int left = L; int right = R - 1; while (left <= right) { int mid = left + ((right - left) >> 1); if (posArr[mid] < posArr[R]) { M = mid; left = mid + 1; } else { right = mid - 1; } } head.left = process2(posArr, L, M); head.right = process2(posArr, M + 1, R - 1); return head; }