Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Analyse:the core idea of this problem are the same as Convert Sorted Array to Binary Search Tree. For a list, it's hard to access the elements randomly, we had to compute the list ' s length and sequencely locate a Specif IC element.
Trial 1:construct a function s.t. For a given index, it returns find its corresponding listnode.
Na:time LIMITED.
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 /**Ten * Definition for a binary tree node. One * struct TreeNode { A * int val; - * TreeNode *left; - * TreeNode *right; the * TreeNode (int x): Val (x), left (null), right (null) {} - * }; - */ - classSolution { + Public: -treenode* Sortedlisttobst (listnode*head) { + if(!head)returnNULL; A at intLen =0;//length of the list -listnode* move =head; - while(move) { -move = move->Next; -len++; - } in returnConstruct (head,0, Len-1); - } to +treenode* construct (listnode* head,intLowintHigh ) { - if(Low > High)returnNULL; the * intMid = (low + high)/2; $listnode* Targetlistnode =Nodeatindex (head, mid);Panax Notoginsengtreenode* root =NewTreeNode (targetlistnode->val); - if(Low = = high)returnRoot; the +Root->left = construct (head, low, mid-1); ARoot->right = Construct (head, MID +1, high); the + returnRoot; - } $ $listnode* Nodeatindex (listnode* head,intindex) { - if(Index <0|| !head)returnNULL; - thelistnode* move =head; - intCount =0;//index of the first node in the list is 0Wuyi while(Count! =index) { themove = move->Next; -count++; Wu } - returnmove; About } $};View Code
Trial 2:then I wanna be opportunistic. I pushed every value in the list into a vector and tried to use the original code I wrote before. hahaha
Runtime:32ms.
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 /**Ten * Definition for a binary tree node. One * struct TreeNode { A * int val; - * TreeNode *left; - * TreeNode *right; the * TreeNode (int x): Val (x), left (null), right (null) {} - * }; - */ - classSolution { + Public: -treenode* Sortedlisttobst (listnode*head) { + if(!head)returnNULL; A atvector<int> VEC;//convert this question to a simpler one ^_^ -listnode* move =head; - while(move) { -Vec.push_back (move->val); -move = move->Next; - } in - returnConvert (VEC,0, Vec.size ()-1); to } +treenode* CONVERT (vector<int>& Nums,intLowintHigh ) { - if(Low > High)returnNULL; the * intMid = (low + high)/2; $treenode* root =NewTreeNode (Nums[mid]);Panax Notoginseng if(Low = = high)returnRoot; - theRoot->left = CONVERT (Nums, low, mid-1); +Root->right = Convert (nums, Mid +1, high); A the returnRoot; + } -};View Code
Convert Sorted List to Binary Search Tree