LeetCode题解之 Convert Sorted Array to Binary Search Tree

时间:2024-04-11 14:06:41

1、题目描述

LeetCode题解之 Convert Sorted Array to Binary Search Tree

2、问题分析

使用二分法即可。

3、代码

 TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.size() == )
return NULL; int left = ;
int right = nums.size() - ; TreeNode *node = new TreeNode();
BST(node->left,nums, left, right);
return node->left; } void BST(TreeNode * &parent, vector<int> &nums,int left, int right)
{ if (left <= right) {
int mid = (left + right)/;
TreeNode *node = new TreeNode(nums[mid]);
parent = node;
BST(node->left, nums, left, mid - );
BST(node->right, nums, mid + , right);
} else {
return ;
}
}