leetcode_convert_sorted_list_to_binary_search_tree

难度:Medium

解题思路:采用分治的方法。在链表中找到中间节点,创建树节点,然后截断这个链表,分为两段。再分别调用函数。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return new TreeNode(head->val);
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *slow = dummy;
ListNode *fast = dummy;
while(fast->next != NULL && fast->next->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
slow->next = NULL;
TreeNode *new_node = new TreeNode(fast->val);
new_node->left = sortedListToBST(head);
new_node->right = sortedListToBST(fast->next);
return new_node;
}
};

运行结果:22ms,超过85.76%