-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvertSortedListToBinarySearchTree.h
76 lines (74 loc) · 1.58 KB
/
ConvertSortedListToBinarySearchTree.h
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
*Solution 1
*Top-down dfs
*time: space:
*/
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
return dfs(head,NULL);
}
private:
TreeNode *dfs(ListNode *start,ListNode *end)
{
if(start==end)return NULL;
ListNode *p=start,*q=start;
while(q!=end&&q->next!=end)//快慢指针找中点
{
p=p->next;
q=q->next->next;
}
TreeNode *root=new TreeNode(p->val);
root->left=dfs(start,p);
root->right=dfs(p->next,end);
return root;
}
};
/**
*Solution 2
*Bottom-up dfs
*time: space:
*/
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
int len=0;
ListNode *p=head;
while(p)
{
++len;
p=p->next;
}
return dfs(head,0,len-1);
}
private:
TreeNode *dfs(ListNode *&head,int start,int end)
{
if(start>end)return NULL;
TreeNode *parent=NULL,*leftChild=NULL;
int mid=start+(end-start)/2;
leftChild=dfs(head,start,mid-1);
parent=new TreeNode(head->val);
parent->left=leftChild;
head=head->next;
parent->right=dfs(head,mid+1,end);
return parent;
}
};