|
| 1 | +/* |
| 2 | +Convert Sorted List to Binary Search Tree |
| 3 | +============================================ |
| 4 | +
|
| 5 | +Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. |
| 6 | +
|
| 7 | +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. |
| 8 | +
|
| 9 | +Example 1: |
| 10 | +Input: head = [-10,-3,0,5,9] |
| 11 | +Output: [0,-3,9,-10,null,5] |
| 12 | +Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. |
| 13 | +
|
| 14 | +Example 2: |
| 15 | +Input: head = [] |
| 16 | +Output: [] |
| 17 | +
|
| 18 | +Example 3: |
| 19 | +Input: head = [0] |
| 20 | +Output: [0] |
| 21 | +
|
| 22 | +Example 4: |
| 23 | +Input: head = [1,3] |
| 24 | +Output: [3,1] |
| 25 | +
|
| 26 | +Constraints: |
| 27 | +The number of nodes in head is in the range [0, 2 * 104]. |
| 28 | +-10^5 <= Node.val <= 10^5 |
| 29 | +*/ |
| 30 | + |
| 31 | +/** |
| 32 | + * Definition for singly-linked list. |
| 33 | + * struct ListNode { |
| 34 | + * int val; |
| 35 | + * ListNode *next; |
| 36 | + * ListNode() : val(0), next(nullptr) {} |
| 37 | + * ListNode(int x) : val(x), next(nullptr) {} |
| 38 | + * ListNode(int x, ListNode *next) : val(x), next(next) {} |
| 39 | + * }; |
| 40 | + */ |
| 41 | +/** |
| 42 | + * Definition for a binary tree node. |
| 43 | + * struct TreeNode { |
| 44 | + * int val; |
| 45 | + * TreeNode *left; |
| 46 | + * TreeNode *right; |
| 47 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 48 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 49 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 50 | + * }; |
| 51 | + */ |
| 52 | + |
| 53 | +class Solution |
| 54 | +{ |
| 55 | +public: |
| 56 | + TreeNode *sortedListToBST(ListNode *head, ListNode *tail = NULL) |
| 57 | + { |
| 58 | + if (head == tail) |
| 59 | + return NULL; |
| 60 | + if (head->next == tail) |
| 61 | + { |
| 62 | + TreeNode *root = new TreeNode(head->val); |
| 63 | + return root; |
| 64 | + } |
| 65 | + |
| 66 | + auto fast = head, slow = head; |
| 67 | + while (fast != tail && fast->next != tail) |
| 68 | + { |
| 69 | + fast = fast->next->next; |
| 70 | + slow = slow->next; |
| 71 | + } |
| 72 | + |
| 73 | + TreeNode *root = new TreeNode(slow->val); |
| 74 | + root->left = sortedListToBST(head, slow); |
| 75 | + root->right = sortedListToBST(slow->next, tail); |
| 76 | + |
| 77 | + return root; |
| 78 | + } |
| 79 | +}; |
0 commit comments