106. The sorted list is converted to a two -point lookup tree
- Describe
- Notes
- Data
- Evaluation
Gives a single linked list of all elements in ascending order, converting it into a highly balanced binary search tree
Have you ever encountered this problem in a real interview? Yes
Sample Example
21->2->3 => / 1 3
label Links List recursion
/** * Definition of ListNode * class ListNode {* Public: * int val; * ListNode *next; * ListNode (int val) {* This->val = val; * This->next = NULL; *} *} * Definition of TreeNode: * Class TreeNode {* Public: * int val; * TreeNode *left, *right; * Tree Node (int val) {* This->val = val; * This->left = This->right = NULL; *} *} */class Solutio n {public:/** * @param head:the first node of linked list. * @return: A tree node */TreeNode *sortedlisttobst (ListNode *head) {//write your code here//with recursion treenode* root = nullptr; if (head! = nullptr) {ListNode *left = nullptr, *right = nullptr; root = new TreeNode (Dichotomylist (head, left, right)); Root->left = Sortedlisttobst (left); Root->right = Sortedlisttobst (right); }} int Dichotomylist (ListNode *head, ListNode *&left, ListNode *&right) {if (Head->next! = Nullpt R {ListNode *fast = head, *slow = head, *temp = head; while (fast! = nullptr && Fast->next! = nullptr) {temp = slow; slow = slow->next; Fast = fast->next->next; } temp->next = nullptr; left = head; right = slow->next; Return slow->val; } else {left = nullptr; right = nullptr; Return head->val; } }};
106. The sorted list is converted to a two-point lookup tree