LeetCode109 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. (Medium)

分析: 

链表不同于数组的是需要先遍历一遍求出长度,然后再找到中点,其余思路与Convert Sorted Array to Binary Search Tree一致。

代码:

 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 private:
20     TreeNode* helper(ListNode* head, int sz) {
21         if (head == nullptr || sz <= 0) {
22             return nullptr;
23         }
24         ListNode* runner = head;
25         for (int i = 0; i < sz / 2; ++i) {
26             runner = runner -> next;
27         }
28         TreeNode* root = new TreeNode(runner -> val);
29         root -> left = helper(head, sz / 2);
30         root -> right = helper(runner -> next, sz - sz / 2 - 1);
31         return root;
32     }
33 public:
34     TreeNode* sortedListToBST(ListNode* head) {
35         int sz = 0;
36         ListNode* runner = head;
37         while (runner != nullptr) {
38             sz++;
39             runner = runner -> next;
40         }
41         TreeNode* result = helper(head, sz);
42         return result;
43     }
44 };

 

posted @ 2016-11-07 19:30  wangxiaobao1114  阅读(210)  评论(0编辑  收藏  举报