这题跟 #108 将有序数组转换成二叉搜索树 一个是有序链表,一个是有序数组,
链表不方便索引查找,这里直接把链表转换成数组就完事了!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* build(int *nums, int left, int right)
{
if(left > right) return NULL;
int mid = (left + right + 1) / 2;
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = nums[mid];
root->left = build(nums, left, mid-1);
root->right = build(nums, mid+1, right);
return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize)
{
if (numsSize == 0) return NULL;
return build(nums, 0, numsSize-1);
}
struct TreeNode* sortedListToBST(struct ListNode* head){
if(!head) return NULL;
int numsSize = 0;
struct ListNode *p = head;
while(p)
{
numsSize++;
p = p->next;
}
int *nums = (int *)malloc(sizeof(int) * numsSize);
memset(nums, 0, sizeof(int) * numsSize);
int i;
for(i = 0; i<numsSize; ++i)
{
nums[i] = head->val;
head = head->next;
}
return sortedArrayToBST(nums, numsSize);
}