forked from daizhenyang/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvert Sorted List to Binary Search Tree.cpp
More file actions
52 lines (52 loc) · 1.16 KB
/
Convert Sorted List to Binary Search Tree.cpp
File metadata and controls
52 lines (52 loc) · 1.16 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
/**
* 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) {}
* };
*/
class Solution {
public:
TreeNode *buildBalance(int len)
{
if (!len)return NULL;
int r=len/2;int l=r;
if (len%2==0)l--;
TreeNode *p=new TreeNode(0);
p->left=buildBalance(l);
p->right=buildBalance(r);
return p;
}
void inorder(TreeNode *p,ListNode * &head)
{
if (!p)return;
inorder(p->left,head);
p->val=head->val;
head=head->next;
inorder(p->right,head);
}
TreeNode *sortedListToBST(ListNode * head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *ptr=head;
int len=0;
while (ptr)
{
len++;
ptr=ptr->next;
}
TreeNode *p=buildBalance(len);
inorder(p,head);
return p;
}
};