leetcode_question_109 Convert Sorted List to Binary Search Tree

来源:互联网 发布:vmware桥接网络设置 编辑:程序博客网 时间:2024/05/01 09:48

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() functionif(head==NULL)return NULL;        return tobst(head,NULL);    }};


原创粉丝点击