Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
采用二分递归。
1 class Solution { 2 public: 3 TreeNode *createTree(vector<int> &num,int begin,int end) 4 { 5 if(begin>end) return NULL; 6 int mid=(begin+end)/2; 7 TreeNode *root=new TreeNode(num[mid]); 8 root->left=createTree(num,begin,mid-1); 9 root->right=createTree(num,mid+1,end); 10 return root; 11 } 12 13 TreeNode *sortedArrayToBST(vector<int> &num) { 14 if(num.size()==0) return NULL; 15 return createTree(num,0,num.size()-1); 16 } 17 };
时间: 2024-12-18 07:37:46