Description
Submission
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
TreeNode* dfs(ListNode* left, ListNode* right) {
if(left == nullptr) return nullptr;
if(left == right) return new TreeNode(left->val);
// cout << left->val;
if(left->next == right) {
TreeNode* r = nullptr;
if(right) r = new TreeNode(right->val);
return new TreeNode(left->val, nullptr, r);
}
ListNode *slow = left, *fast = left, *prevSlow = left;
for(; fast != right && fast->next != right; prevSlow = slow, slow = slow->next, fast = fast->next->next);
return new TreeNode(
slow->val,
dfs(left, prevSlow),
dfs(slow->next, right)
);
}
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head == nullptr) return nullptr;
return dfs(head, nullptr);
}
};