-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet109.cpp
More file actions
56 lines (53 loc) · 1.29 KB
/
Copy pathleet109.cpp
File metadata and controls
56 lines (53 loc) · 1.29 KB
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
/**
* 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 ;
ListNode *x = head ;
int len = 0 ;
while(x != NULL){
len++ ;
x = x->next ;
}
return generateSubTree(head, len);
}
TreeNode* generateSubTree(ListNode* st, int m){
if(st == NULL || m<=0)
return NULL ;
if(m==1){
TreeNode *t = new TreeNode(st->val) ;
return t ;
}
ListNode* z = getNode(st, m/2) ;
TreeNode *root = new TreeNode(z->val) ;
root->left = generateSubTree(st,m/2) ;
root->right = generateSubTree(z->next, (m-1)/2) ;
return root ;
}
ListNode* getNode(ListNode* head, int n){
int x = 0 ;
ListNode* y = head ;
while(y != NULL && x<n){
y = y->next ;
x++ ;
}
return y ;
}
};