Skip to content

Commit 550a49b

Browse files
committed
feat:add Solution.cpp for 0109.Convert Sorted List to Binary Search Tree
1 parent 1f35106 commit 550a49b

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public:
3+
TreeNode* sortedListToBST(ListNode* head) {
4+
if (!head) return nullptr;
5+
if (!head->next) return new TreeNode(head->val);
6+
ListNode *fast = head, *slow = head, *last = slow;
7+
while (fast->next && fast->next->next) {
8+
last = slow;
9+
slow = slow->next;
10+
fast = fast->next->next;
11+
}
12+
fast = slow->next;
13+
last->next = nullptr;
14+
TreeNode *cur = new TreeNode(slow->val);
15+
if (head != slow) cur->left = sortedListToBST(head);
16+
cur->right = sortedListToBST(fast);
17+
return cur;
18+
}
19+
};

0 commit comments

Comments
 (0)