1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
convert-sorted-list-to-binary-search-tree.cpp 1.09 KB
一键复制 编辑 原始数据 按行查看 历史
// Time: O(n)
// Space: O(logn)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
auto curr = head;
int n = 0;
while (curr) {
curr = curr->next;
++n;
}
return BuildBSTFromSortedDoublyListHelper(&head, 0, n);
}
TreeNode * BuildBSTFromSortedDoublyListHelper(ListNode **head, int s, int e) {
if (s == e) {
return nullptr;
}
int m = s + ((e - s) / 2);
auto left = BuildBSTFromSortedDoublyListHelper(head, s, m);
auto curr = new TreeNode((*head)->val);
*head = (*head)->next;
curr->left = left;
curr->right = BuildBSTFromSortedDoublyListHelper(head, m + 1, e);
return curr;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助