|
| 1 | +# 题目描述 |
| 2 | +Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. |
| 3 | + |
| 4 | +# 思想 |
| 5 | +找出中间节点,然后断开,构造出二分查找树 |
| 6 | + |
| 7 | +# 代码一 |
| 8 | +对于中间节点的处理:直接令成nullptr |
| 9 | +```c |
| 10 | +/** |
| 11 | + * Definition for singly-linked list. |
| 12 | + * struct ListNode { |
| 13 | + * int val; |
| 14 | + * ListNode *next; |
| 15 | + * ListNode(int x) : val(x), next(NULL) {} |
| 16 | + * }; |
| 17 | + */ |
| 18 | +/** |
| 19 | + * Definition for binary tree |
| 20 | + * struct TreeNode { |
| 21 | + * int val; |
| 22 | + * TreeNode *left; |
| 23 | + * TreeNode *right; |
| 24 | + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 25 | + * }; |
| 26 | + */ |
| 27 | +class Solution { |
| 28 | +public: |
| 29 | + TreeNode *sortedListToBST(ListNode *head) { |
| 30 | + if (head == nullptr) |
| 31 | + return nullptr; |
| 32 | + if (head->next == nullptr) |
| 33 | + return new TreeNode(head->val); |
| 34 | + ListNode *preMid = nullptr; |
| 35 | + ListNode *mid = head; |
| 36 | + ListNode *end = head; |
| 37 | + while(end != nullptr && end->next != nullptr) |
| 38 | + { |
| 39 | + preMid = mid; |
| 40 | + mid = mid->next; |
| 41 | + end = end->next->next; |
| 42 | + } |
| 43 | + TreeNode *root = new TreeNode(mid->val); |
| 44 | + preMid->next = nullptr; |
| 45 | + |
| 46 | + root->left = sortedListToBST(head); |
| 47 | + root->right = sortedListToBST(mid->next); |
| 48 | + |
| 49 | + return root; |
| 50 | + } |
| 51 | +}; |
| 52 | +``` |
| 53 | + |
| 54 | +# 代码二 |
| 55 | +对于中间节点的处理:记录下来。换句话说,不令成nullptr,知道是中间节点即可 |
| 56 | +```c |
| 57 | +/** |
| 58 | + * Definition for singly-linked list. |
| 59 | + * struct ListNode { |
| 60 | + * int val; |
| 61 | + * ListNode *next; |
| 62 | + * ListNode(int x) : val(x), next(NULL) {} |
| 63 | + * }; |
| 64 | + */ |
| 65 | +/** |
| 66 | + * Definition for binary tree |
| 67 | + * struct TreeNode { |
| 68 | + * int val; |
| 69 | + * TreeNode *left; |
| 70 | + * TreeNode *right; |
| 71 | + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 72 | + * }; |
| 73 | + */ |
| 74 | +class Solution { |
| 75 | +public: |
| 76 | + TreeNode *sortedListToBST(ListNode *head) { |
| 77 | + return makeBST(head, nullptr); |
| 78 | + } |
| 79 | + |
| 80 | + TreeNode *makeBST(ListNode *head, ListNode *end){ |
| 81 | + if(head == end) |
| 82 | + return nullptr; |
| 83 | + ListNode *mid = head; |
| 84 | + ListNode *fast = head; |
| 85 | + while(fast != end && fast->next != end){ |
| 86 | + mid = mid->next; |
| 87 | + fast = fast->next->next; |
| 88 | + } |
| 89 | + TreeNode *root = new TreeNode(mid->val); |
| 90 | + root->left = makeBST(head, mid); |
| 91 | + root->right = makeBST(mid->next, end); |
| 92 | + |
| 93 | + return root; |
| 94 | + } |
| 95 | +}; |
| 96 | +``` |
0 commit comments