您的位置:首页 > 其它

leetcode[109]:Convert Sorted List to Binary Search Tree

2015-07-26 19:17 549 查看
Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

/**
* 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* sortedArrayToBST(int* nums, int numsSize) {

struct TreeNode* tmp;
if(numsSize==0) return NULL;
tmp=(struct TreeNode*)malloc(sizeof(struct TreeNode*));
tmp->val=nums[numsSize/2];

tmp->left=sortedArrayToBST(nums, numsSize/2);
if(numsSize%2==0) tmp->right=sortedArrayToBST(nums+numsSize/2+1, numsSize/2-1);
else  tmp->right=sortedArrayToBST(nums+numsSize/2+1, numsSize/2);
return tmp;

}

struct TreeNode* sortedListToBST(struct ListNode* head) {
int num[100000],i,j;

for(i=0;head;i++)
{
num[i]=head->val;
head=head->next;
}

return sortedArrayToBST(num, i);
}


将有序链表遍历成有序数组,再用leetcode[108]:Convert Sorted Array to Binary Search Tree的方法即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  binary tree linkedlist