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