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.
地址:https://oj.leetcode.com/problems/convert-sorted-array-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 if(num.empty()){
14 return NULL;
15 }
16 return subSorted(num,0,num.size()-1);
17 }
18 TreeNode *subSorted(vector<int> &num, int begin, int end){
19 if(begin == end){
20 TreeNode *p = new TreeNode(num[begin]);
21 return p;
22 }
23 int mid = (begin + end) / 2;
24 TreeNode *root = new TreeNode(num[mid]);
25 if(mid > begin){
26 root->left = subSorted(num,begin,mid-1);
27 }
28 root->right = subSorted(num,mid+1,end);
29 return root;
30 }
31 };