Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
I think if it's just a binary tree, there's no difficulty, but if it's a balanced binary tree, it might be difficult.
Requires the height of the left and right subtree to be balanced.
First give their own solution, very low, is now the node is stored in the vector, in the selection of mid for recursive creation
Time, Space complexity O (n)
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; *//** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {Public:treenode *sortedlisttobst (ListNode *head) {//< Here at the beginning of the thought is that the list of processing is very inconvenient, I hope to be able to put the vector first Middle Vector<treenode*> NodeList; if (head = = null) {return null; } TreeNode * Phead = new TreeNode (head->val); Nodelist.push_back (Phead); while (head->next! = NULL) {head = head->next; TreeNode * node = new TreeNode (head->val); Nodelist.push_back (node); } return BST (0,nodelist.size () -1,nodelist);//< represents the initial value, and the end value} TreeNode *bst (int start,int end,vector<tree Node*> NodeList) {if (start = = end) {return nodelist[start]; The If ((start+1) = = end)//< is sorted in the direction of the increased value, then placed directly in the right child's position {nodelist[start]->right = Nodelist[end]; return Nodelist[start]; } int Mid = (start+end)/2; TreeNode *root = Nodelist[mid]; Root->left = BST (start,mid-1,nodelist); Root->right = BST (mid+1,end,nodelist); return root; }};
The following is the standard answer, the time complexity is O (N), the space Complexity of O (1)
But in the recursive process of the whole subtree, I mean, I'm still going around.
TreeNode *sortedlisttobst (ListNode *head) { int len = 0; ListNode * node = head; while (node! = NULL) { node = node->next; len++; } Return Buildtree (head, 0, len-1); } TreeNode *buildtree (listnode *&node, int start, int end) { if (Start > End) return NULL; int mid = start + (End-start)/2; TreeNode *left = buildtree (node, start, mid-1); TreeNode *root = new TreeNode (node->val); < return time indicates the last layer in start = = Mid, so this point is mid point root->left = left; node = node->next; Root->right = buildtree (node, mid+1, end); return root; }
Leetcoode-**convert Sorted list to binary Search Tree represents a single-linked list as a balanced binary