File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments