您的位置:首页 > 其它

Convert Sorted Array to Binary Search Tree

2015-07-31 10:38 417 查看
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Analyse: Using binary search to divide the sorted array into two parts, then recursively do the same process for the two parts.

Runtime: 16ms.

Additional: IT'S THE FIRST TIME I COME UP WITH A SOLUTION WITHOUT REFERENCE. CONG!!

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size() == 0) return NULL;

return convert(nums, 0, nums.size() - 1);
}
TreeNode* convert(vector<int>& nums, int low, int high){
if(low > high) return NULL;

int mid = (low + high) / 2;
TreeNode* root = new TreeNode(nums[mid]);
if(low == high) return root;

root->left = convert(nums, low, mid - 1);
root->right = convert(nums, mid + 1, high);

return root;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: