Skip to content

Commit dd58808

Browse files
committed
Merge branch 'master' of https://github.com/daiwb/Algorithm
2 parents 02435a0 + 23ced1d commit dd58808

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

LeetCode/sortedListToBST.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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 binary tree
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+
public:
20+
TreeNode *doit(ListNode* &head, int st, int ed) {
21+
if (st > ed) return NULL;
22+
int md = (st + ed) / 2;
23+
TreeNode *lTree = doit(head, st, md - 1);
24+
TreeNode *par = new TreeNode(head->val);
25+
head = head->next;
26+
TreeNode *rTree = doit(head, md + 1, ed);
27+
par->left = lTree;
28+
par->right = rTree;
29+
return par;
30+
}
31+
TreeNode *sortedListToBST(ListNode *head) {
32+
if (head == NULL) return NULL;
33+
int len = 0;
34+
ListNode *t = head;
35+
while (t) {
36+
++len;
37+
t = t->next;
38+
}
39+
return doit(head, 1, len);
40+
}
41+
};

0 commit comments

Comments
 (0)