LeetCode OJ:Convert Sorted Array to Binary Search Tree(将排序好的数组转换成二叉搜索树)

时间:2024-04-11 13:36:41

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

讲一个排序好的数组转换成二叉搜索树,这题没想出来,基本上是参考别人的,边界条件应该注意一下:

 /**
* 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 createTree(nums, , nums.size() - );
} TreeNode * createTree(vector<int> & nums, int left, int right)
{
if(left > right)
return NULL;
int mid = left + (right - left)/;
TreeNode * leftNode = createTree(nums, left, mid - );
TreeNode * rightNode = createTree(nums, mid + , right);
TreeNode * tmpRoot= new TreeNode(nums[mid]);
tmpRoot->left = leftNode;
tmpRoot->right = rightNode;
return tmpRoot;
}
};

java版本的代码如下所示,看到排好序的其实就应该注意一点了,自己肯定是不需要再进行比较插入的:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return createTree(nums, 0, nums.length - 1);
} public TreeNode createTree(int[] nums, int left, int right){
if(left > right)
return null;
int mid = left + (right-left) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = createTree(nums, left, mid - 1);
root.right = createTree(nums, mid + 1, right);
return root;
}
}