106. The sorted list is converted to a two-point lookup tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.