LeetCode Convert Sorted Array to Binary Search Tree, Oct 2 '12
G家面试题,写一个吧。
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
TreeNode *sortedArrayToBST(vector<int> &num, int start, int end){
if(start > end) return NULL;
int mid = (start + end)/2;
TreeNode *root = new TreeNode(num[mid]);
root->left = sortedArrayToBST(num, start, mid - 1);
root->right = sortedArrayToBST(num, mid+1, end);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
if(num.size() == 0) return NULL;
return sortedArrayToBST(num, 0, num.size() - 1);
}
No comments:
Post a Comment