問題描述:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/點擊打開鏈接
問題分析:
num[start, end] 有序數組轉換成平衡BST
1. 取出數組中間元素將數組劃分成相等的兩部分。
2. num[start, mid - 1]中是左子樹, num[mid + 1, end] 中是右子樹,num[mid] 是根。
3. 以上過程遞歸構造各自子樹。
示例代碼:
TreeNode *sortedAarrytoTree(vector<int> &num, int start, int end)
{
if (start > end) return NULL;
int cur = (start + end) / 2;
TreeNode *root = new TreeNode(num[cur]);
root->left = sortedAarrytoTree(num, start, cur - 1);
root->right = sortedAarrytoTree(num, cur + 1, end);
return root;
}