Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
讲一个排序好的数组转换成二叉搜索树,这题没想出来,基本上是参考别人的,边界条件应该注意一下:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* sortedArrayToBST(vector<int>& nums) { 13 return createTree(nums, 0, nums.size() - 1); 14 } 15 16 TreeNode * createTree(vector<int> & nums, int left, int right) 17 { 18 if(left > right) 19 return NULL; 20 int mid = left + (right - left)/2; 21 TreeNode * leftNode = createTree(nums, left, mid - 1); 22 TreeNode * rightNode = createTree(nums, mid + 1, right); 23 TreeNode * tmpRoot= new TreeNode(nums[mid]); 24 tmpRoot->left = leftNode; 25 tmpRoot->right = rightNode; 26 return tmpRoot; 27 } 28 };
时间: 2024-12-19 21:05:46