首页 > 代码库 > 【Lintcode】106.Convert Sorted List to Balanced BST
【Lintcode】106.Convert Sorted List to Balanced BST
题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Example
2
1->2->3 => / 1 3
题解:
Solution 1 ()
class Solution { public: TreeNode *sortedListToBST(ListNode *head) { if (!head) return nullptr; return sortedListToBST(head, nullptr); } TreeNode *sortedListToBST(ListNode* head, ListNode* tail) { if (head == tail) return nullptr; ListNode* mid = head, *tmp = head; while (tmp != tail && tmp->next != tail) { mid = mid->next; tmp = tmp->next->next; } TreeNode* root = new TreeNode(mid->val); root->left = sortedListToBST(head, mid); root->right = sortedListToBST(mid->next, tail); return root; } };
Solution 2 ()
class Solution { public: TreeNode* sortedListToBST(ListNode* head) { if (head == nullptr) return nullptr; ListNode* fast = head; ListNode* slow = head; ListNode* prev = nullptr; while (fast != nullptr && fast->next != nullptr) { fast = fast->next->next; prev =slow; slow = slow->next; } TreeNode* root = new TreeNode(slow->val); if (prev != nullptr) prev->next = nullptr; else head = nullptr; root->left = sortedListToBST(head); root->right = sortedListToBST(slow->next); return root; } };
【Lintcode】106.Convert Sorted List to Balanced BST
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。