Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

C++:
01 /**
02  * Definition for singly-linked list.
03  * struct ListNode {
04  *     int val;
05  *     ListNode *next;
06  *     ListNode(int x) : val(x), next(NULL) {}
07  * };
08  */
09 /**
10  * Definition for binary tree
11  * struct TreeNode {
12  *     int val;
13  *     TreeNode *left;
14  *     TreeNode *right;
15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
16  * };
17  */
18  TreeNode* sortedListToBSTHelper(ListNode*& head, int start, int end)
19  {
20     if((start>end)||(head==NULL))
21         return NULL;
22     int middle=(start+end)/2;
23     TreeNode* left=sortedListToBSTHelper(head,start,middle1);
24     TreeNode* A=new TreeNode(head->val);
25     head=head->next;
26     TreeNode* right=sortedListToBSTHelper(head,middle+1,end);
27     A->left=left;
28     A->right=right;
29     return A;
30  }
31 
32 class Solution {
33 public:
34     TreeNode *sortedListToBST(ListNode *head) {
35         // Start typing your C/C++ solution below
36         // DO NOT write int main() function
37         int i=0;
38         ListNode* count=head;
39         while(count!=NULL)
40         {
41             i++;
42             count=count->next;
43         }
44         return sortedListToBSTHelper(head,0,i);
45     }
46 };
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