Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Hide Tagsdepth-first Search Linked List The problem is to turn the list into a two-fork tree, the cumbersome traversal process, because of the constraints of the list, so the order of deep search happens to be the order of the list, by setting the parameters of the recursive function, can be in depth search time can be traversed.
TreeNode * Help_f (ListNode *&curlist,int lft,int RGT)
All code:
#include <iostream>using namespacestd;/** * Definition for singly-linked list.*/structListNode {intVal; ListNode*Next; ListNode (intx): Val (x), Next (NULL) {}};/** * definitiosn for binary tree*/structTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: TreeNode*sortedlisttobst (ListNode *head) { intlen=0; ListNode* p =Head; while(p!=NULL) {Len++; P=p->Next; }//cout<<len<<endl; returnHelp_f (Head,0, len-1); } TreeNode* Help_f (ListNode *&curlist,intLfTintRGT) { if(LFT>RGT)returnNULL; intMid= (LFT+RGT)/2; TreeNode*LFTCLD = Help_f (curlist,lft,mid-1); TreeNode*parent =NewTreeNode (curlist->val); Parent->left=LFTCLD; Curlist=curlist->Next; Parent->right=help_f (curlist,mid+1, RGT); returnparent; }};intMain () {ListNode N1 (0); Solution Sol; Sol.sortedlisttobst (&N1); return 0;}
[Leetcode] Convert Sorted List to Binary search Tree DFS, deep Search