Convert Sorted list to Binary Search Tree--Leetcodegiven a singly linked List where elements is s

Source: Internet
Author: User

Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.


Basic ideas:

The process of the middle sequence traversal, which corresponds to the order of the ordered list, is one by one.

The construction of the tree is constructed by the middle sequence traversal.

and using the range of values, determine the location of the root, as well as the extent of the subtree.

Therefore, it is necessary to traverse the whole list to obtain the total length.

The half of the list length is the location of the root node. The left is the value range of the Zuozi, and the right is the range of values for the rightmost subtree.

As above, recursion is applied to the left subtree, right sub-tree. Gradually shrinks the range until the leaf node.


/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; *//** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}};        */class Solution {public:treenode* Sortedlisttobst (listnode* head) {int size = 0;        ListNode *p = head;            while (p) {++size;        p = p->next;    } return Helper (head, 0, size-1);        } TreeNode *helper (ListNode *&head, int start, int stop) {if (Start > Stop) return 0;        const int MID = start + (Stop-start)/2;        TreeNode *left = Helper (head, start, mid-1);        TreeNode *root = new TreeNode (head->val);        Root->left = left;        Head = head->next;        Root->right = Helper (head, mid+1, stop);    return root; }};


Convert Sorted list to Binary Search Tree--Leetcodegiven a singly linked List where elements is s

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.