0%

LeetCode: Convert Sorted List to Binary Search Tree

蛮好的一条题。分治,单链表不像数组一样可以随机访问,所以每一次需要遍历一次获取中间节点。

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
42
43
44
/**
* 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) {
ListNode* end=NULL;
return foo(head,end);
}

TreeNode* foo(ListNode* begin, ListNode *end)
{
if(begin==NULL || begin==end)
return NULL;
auto mid=begin;
auto right=begin->next;
while(right!=end)
{
mid=mid->next;
if(right->next==end)
right=right->next;
else
right=right->next->next;
}
auto root=new TreeNode(mid->val);
root->left=foo(begin,mid);
root->right=foo(mid->next,end);
return root;
}
};