Leetcode:Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
分析:对于BST,左右子树的高度差小于等于1,则在由sorted array构建BST时把数组中间元素作为根节点,然后递归的构建左右子树。代码如下:
1 class Solution { 2 public: 3 TreeNode *sortedArrayToBST(vector<int> &num) { 4 return build_BST(num, 0, num.size()-1); 5 } 6 7 TreeNode *build_BST(vector<int> &num, int start, int end){ 8 if(start > end) return NULL; 9 10 int mid = (start + end)/2; 11 TreeNode *root = new TreeNode(num[mid]); 12 root->left = build_BST(num, start, mid-1); 13 root->right = build_BST(num, mid+1, end); 14 15 return root; 16 } 17 };