Boostable

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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 };

 

posted on 2014-08-27 21:19  Boostable  阅读(149)  评论(0编辑  收藏  举报