-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path109.convert-sorted-list-to-binary-search-tree.cpp
109 lines (105 loc) · 2.4 KB
/
109.convert-sorted-list-to-binary-search-tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
* @lc app=leetcode id=109 lang=cpp
*
* [109] Convert Sorted List to Binary Search Tree
*
* https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/
*
* algorithms
* Medium (49.62%)
* Likes: 3136
* Dislikes: 98
* Total Accepted: 306.4K
* Total Submissions: 591.1K
* Testcase Example: '[-10,-3,0,5,9]'
*
* Given the head of a singly linked list where elements are sorted in
* ascending order, convert it to a height balanced BST.
*
* For this problem, a height-balanced binary tree is defined as a binary tree
* in which the depth of the two subtrees of every node never differ by more
* than 1.
*
*
* Example 1:
*
*
* Input: head = [-10,-3,0,5,9]
* Output: [0,-3,9,-10,null,5]
* Explanation: One possible answer is [0,-3,9,-10,null,5], which represents
* the shown height balanced BST.
*
*
* Example 2:
*
*
* Input: head = []
* Output: []
*
*
* Example 3:
*
*
* Input: head = [0]
* Output: [0]
*
*
* Example 4:
*
*
* Input: head = [1,3]
* Output: [3,1]
*
*
*
* Constraints:
*
*
* The number of nodes in head is in the range [0, 2 * 10^4].
* -10^5 <= Node.val <= 10^5
*
*
*/
// @lc code=start
/**
* 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 {
public:
TreeNode* sortedListToBST(ListNode* head) {
return toBST(head, nullptr);
}
TreeNode* toBST(ListNode* head, ListNode* tail) {
if (head == tail)
return nullptr;
ListNode* fast = head;
ListNode* slow = head;
while (fast != tail && fast->next != tail) {
slow = slow->next;
fast = fast->next->next;
}
TreeNode* root = new TreeNode(slow->val);
root->left = toBST(head, slow);
root->right = toBST(slow->next, tail);
return root;
}
};
// @lc code=end