Convert Sorted List to Binary Search Tree [LeetCode]

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

Solution:

 1     TreeNode *sortedListToBST(ListNode *head) {
 2         if(head == NULL)
 3             return NULL;
 4         if(head->next == NULL)
 5             return new TreeNode(head->val);
 6             
 7         ListNode * current = head;
 8         int size = 0;
 9         while(current != NULL){
10             size ++;
11             current = current->next;
12         }
13         current = head;
14         int median = size / 2;
15         int count = 0;
16         ListNode * median_node = NULL;
17         ListNode * pre_node = NULL;
18         while(current != NULL){
19             if(count == median){
20                 median_node = current;
21                 pre_node->next = NULL;
22                 break;
23             }
24             count ++;
25             pre_node = current;
26             current = current->next;
27         }
28         TreeNode * root = new TreeNode(median_node->val);
29         root->left = sortedListToBST(head);
30         root->right = sortedListToBST(median_node->next);
31         return root;
32     }

 

posted @ 2013-11-29 07:41  假日笛声  阅读(174)  评论(0编辑  收藏  举报