Skip to content

Commit 6cb6a37

Browse files
committed
"Convert Sorted List to Binary Search Tree"
1 parent d189284 commit 6cb6a37

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
179179
| 112 | [Path Sum] | [C](src/112.c) |
180180
| 111 | [Minimum Depth of Binary Tree] | [C](src/111.c) |
181181
| 110 | [Balanced Binary Tree] | [C](src/110.c) |
182-
| 109 | [Convert Sorted List to Binary Search Tree] | |
182+
| 109 | [Convert Sorted List to Binary Search Tree] | [C++](src/109.cpp) |
183183
| 108 | [Convert Sorted Array to Binary Search Tree] | [C](src/108.c) |
184184
| 107 | [Binary Tree Level Order Traversal II] | [C++](src/107.cpp) |
185185
| 106 | [Construct Binary Tree from Inorder and Postorder Traversal] | [C](src/106.c) |

src/109.cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
struct ListNode {
7+
int val;
8+
ListNode *next;
9+
ListNode(int x) : val(x), next(NULL) {}
10+
};
11+
12+
struct TreeNode {
13+
int val;
14+
TreeNode *left;
15+
TreeNode *right;
16+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
17+
};
18+
19+
class Solution {
20+
public:
21+
TreeNode* sortedListToBST(ListNode* head) {
22+
if (head == NULL) return NULL;
23+
24+
ListNode *fast, *slow, *prev;
25+
fast = slow = head;
26+
prev = NULL;
27+
while (fast) {
28+
fast = fast->next;
29+
if (!fast) break;
30+
fast = fast->next;
31+
prev = slow;
32+
slow = slow->next;
33+
}
34+
35+
if (slow == NULL) return NULL;
36+
if (prev) prev->next = NULL;
37+
38+
TreeNode *node = new TreeNode(slow->val);
39+
node->left = sortedListToBST(slow == head ? NULL : head);
40+
node->right = sortedListToBST(slow->next);
41+
42+
return node;
43+
}
44+
45+
void preOrderTraversal(TreeNode *root) {
46+
if (root == NULL) return;
47+
48+
printf("%d ", root->val);
49+
preOrderTraversal(root->left);
50+
preOrderTraversal(root->right);
51+
}
52+
};
53+
54+
int main() {
55+
56+
ListNode *head = new ListNode(1);
57+
ListNode *p = head;
58+
for (int i = 2; i <= 7; i++) {
59+
p->next = new ListNode(i);
60+
p = p->next;
61+
}
62+
p->next = NULL;
63+
64+
p = head;
65+
while (p) {
66+
printf("%d ", p->val);
67+
p = p->next;
68+
}
69+
printf("\n");
70+
71+
Solution s;
72+
TreeNode *root = s.sortedListToBST(head);
73+
74+
s.preOrderTraversal(root);
75+
printf("\n");
76+
77+
return 0;
78+
}

0 commit comments

Comments
 (0)