题目描述:
ED2BDC01-E956-4A6B-A1FD-6A7F56A83122.png解题思路:
从一个有序数组中选择一个元素作为根结点,应该选择中间的那个数作为根结点;
然后数组左边的作为左子树,右边的作为右子树
代码:
/**
* 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) {
return sortedArrayToBST(nums, 0, nums.size()-1);
}
TreeNode* sortedArrayToBST(vector<int>& nums, int l, int r) {
if (r < l) return NULL;
int mid = l + ((r-l)>>1);
TreeNode* root = new TreeNode(nums[mid]);
root->left = sortedArrayToBST(nums, l, mid - 1);
root->right = sortedArrayToBST(nums, mid + 1, r);
return root;
}
};
网友评论