Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

C++:
01 /**
02  * Definition for binary tree
03  * struct TreeNode {
04  *     int val;
05  *     TreeNode *left;
06  *     TreeNode *right;
07  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
08  * };
09  */
10  TreeNode* sortedArrayToBSTHelper(vector<int> &num, int start, int end)
11  {
12      if(start>end)
13         return NULL;
14      int middle=(start+end)/2;
15      TreeNode* left=sortedArrayToBSTHelper(num,start,middle1);
16      TreeNode* A=new TreeNode(num[middle]);
17      TreeNode* right=sortedArrayToBSTHelper(num,middle+1,end);
18      A->left=left;
19      A->right=right;
20      return A;
21  }
22 class Solution {
23 public:
24     TreeNode *sortedArrayToBST(vector<int> &num) {
25         // Start typing your C/C++ solution below
26         // DO NOT write int main() function
27         int n=num.size();
28         return sortedArrayToBSTHelper(num,0,n1);
29     }
30 };
Advertisements
This entry was posted in Array and linked list, Recursive, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s