給定一個遞增有序整數數組,構建一棵高度最小的二叉搜索樹(BST)。「最小深度」即高度最小,等價於樹盡可能平衡。
O(n),空間複雜度 O(log n)(遞歸棧)。
TreeNode* buildMinHeightBST(int arr[], int left, int right) {
if (left > right) return NULL;
int mid = left + (right - left) / 2; // 避免溢出,向下取整
TreeNode *root = new TreeNode(arr[mid]);
root->left = buildMinHeightBST(arr, left, mid - 1);
root->right = buildMinHeightBST(arr, mid + 1, right);
return root;
}
TreeNode* buildIterative(int arr[], int n) {
if (n == 0) return NULL;
struct Item { TreeNode **parent; int l, r; };
struct Item stack[n];
int top = 0;
TreeNode *root = NULL;
stack[top++] = (struct Item){&root, 0, n - 1};
while (top) {
struct Item cur = stack[--top];
if (cur.l > cur.r) { *cur.parent = NULL; continue; }
int mid = cur.l + (cur.r - cur.l) / 2;
*cur.parent = new TreeNode(arr[mid]);
stack[top++] = (struct Item){&(*cur.parent)->right, mid + 1, cur.r};
stack[top++] = (struct Item){&(*cur.parent)->left, cur.l, mid - 1};
}
return root;
}
int height(TreeNode *root) {
if (!root) return 0;
return 1 + max(height(root->left), height(root->right));
}
// 對於 n 個節點,最小高度 = floor(log2(n)) + 1
若數組含重複值,BST 定義通常要求「左 ≤ 根 < 右」或「左 < 根 ≤ 右」。選中間元素作為根仍可保證高度最小,只需在分割時明確規則(如 mid 屬於左邊或右邊)。