Topic:Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Thought: Just like the idea above, only notice the way to find the middle node of the list
void Inorder (bintree* root) {if (root = NULL) return; Inorder (Root->left); cout<<root->value<<endl; Inorder (Root->right); }list* Findmid (list*& list,list*& head,list* tail) {list* fast = head; list* slow = head;while (fast! = NULL && Fast->next! = tail) {slow = Slow->next;fast = fast->next;if (fast!) = NULL && Fast->next! = tail) Fast=fast->next;} return slow;} bintree* Helper (list*& root,list*& head,list*& tail) {bintree* node = null;if (head = = Tail | | head = = NULL) retu RN node; list* mid = Findmid (Root,head,tail); list* next = Mid->next;node = new Bintree;node->value = Mid->value;node->left = Node->right = NULL;node-> ; left = helper (root,head,mid); node->right = helper (root,next,tail); return node;} bintree* Convertbst (list*& list) {bintree* root = null;if (list ==null) return root; list* head=list; list* tail=null;root = helper (List,head,tail); return root;} int main () {int array[]={1,2,3,4,5,6,7,8,9,10};//int array[]={1,4,3,2,5,2}; list* list;init_list (list,array,sizeof (array)/sizeof (int)); bintree* root = Convertbst (list); Inorder (root); return 0;}
Convert Sorted List to Binary Search Tree--leetcode