[Leetcode] convert sorted array to binary search tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题意:将已排序的数组转成高度平衡的搜索二叉树。
思路:这题和Convert sorted list to binary search tree 方法一的处理方法基本一样,不同是数组可以直接访问某个元素,而链表不可以。代码如下:
1 /** 2 * Definition for binary tree 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> &num) 13 { 14 if(num.size()==0) return NULL; 15 return reBulidBST(num,0,num.size()-1); 16 } 17 TreeNode *reBulidBST(vector<int> &num,int beg,int end) 18 { 19 if(beg>end) return NULL; 20 21 int mid=beg+(end-beg+1)/2; 22 TreeNode *root=new TreeNode(num[mid]); 23 root->left=reBulidBST(num,beg,mid-1); 24 root->right=reBulidBST(num,mid+1,end); 25 26 return root; 27 } 28 };