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 };
java版本的代码如下所示,看到排好序的其实就应该注意一点了,自己肯定是不需要再进行比较插入的:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode sortedArrayToBST(int[] nums) { 12 return createTree(nums, 0, nums.length - 1); 13 } 14 15 public TreeNode createTree(int[] nums, int left, int right){ 16 if(left > right) 17 return null; 18 int mid = left + (right-left) / 2; 19 TreeNode root = new TreeNode(nums[mid]); 20 root.left = createTree(nums, left, mid - 1); 21 root.right = createTree(nums, mid + 1, right); 22 return root; 23 } 24 }