[LeetCode] Convert Sorted List to Binary Search Tree

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.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 /**
10  * Definition for a binary tree node.
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 class Solution {
19 public:
20     TreeNode* convert(ListNode *&head, int len) {
21         if (len <= 0) return NULL;
22         TreeNode *left = convert(head, len / 2);
23         TreeNode *root = new TreeNode(head->val);
24         root->left = left;
25         head = head->next;
26         root->right = convert(head, len - 1 - len / 2);
27         return root;
28     }
29     TreeNode* sortedListToBST(ListNode* head) {
30         ListNode *p = head;
31         int len = 0;
32         while (p != NULL) {
33             ++len;
34             p = p->next;
35         }
36         return convert(head, len);
37     }
38 };

 

posted @ 2015-10-19 19:49  Eason Liu  阅读(282)  评论(0编辑  收藏  举报