Skip to content

Commit 32e3480

Browse files
committed
Create Convert Sorted List to Binary Search Tree.cpp
1 parent 70c972b commit 32e3480

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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 *buildBalance(int len)
21+
{
22+
if (!len)return NULL;
23+
int r=len/2;int l=r;
24+
if (len%2==0)l--;
25+
TreeNode *p=new TreeNode(0);
26+
p->left=buildBalance(l);
27+
p->right=buildBalance(r);
28+
return p;
29+
}
30+
void inorder(TreeNode *p,ListNode * &head)
31+
{
32+
if (!p)return;
33+
inorder(p->left,head);
34+
p->val=head->val;
35+
head=head->next;
36+
inorder(p->right,head);
37+
}
38+
TreeNode *sortedListToBST(ListNode * head) {
39+
// Start typing your C/C++ solution below
40+
// DO NOT write int main() function
41+
ListNode *ptr=head;
42+
int len=0;
43+
while (ptr)
44+
{
45+
len++;
46+
ptr=ptr->next;
47+
}
48+
TreeNode *p=buildBalance(len);
49+
inorder(p,head);
50+
return p;
51+
}
52+
};

0 commit comments

Comments
 (0)