Convert Sorted List to Binary Search Tree--leetcode

Source: Internet
Author: User

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-&gt ; 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.