您的位置:首页 > 产品设计 > UI/UE

leetcode_question_109 Convert Sorted List to Binary Search Tree

2013-09-23 00:16 489 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a
height balanced BST.

Recursive:

/**
* 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:
void findmid(ListNode* head, ListNode* end, ListNode* &mid)
{
if(head == NULL){mid=NULL; return;}
if(head->next == end){mid=head; return;}
ListNode* pre = head;
mid = head;
while(pre->next != end)
{
pre = pre->next;
if(pre->next != end) pre= pre->next;
else break;
mid = mid->next;
}
}
TreeNode *tobst(ListNode* head, ListNode* tail)
{
if(head == tail)return NULL;
if(head->next == tail)
{
int val = head->val;
delete head;
return new TreeNode(val);
}
ListNode* mid;
findmid(head, tail, mid);
TreeNode* tmp = new TreeNode(mid->val);
tmp->left = tobst(head, mid);
if(mid->next)
tmp->right = tobst(mid->next, tail);
delete mid;
return tmp;
}
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head==NULL)return NULL;
return tobst(head,NULL);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息