[Leetcode] Convert Sorted List to Binary search Tree DFS, deep Search

Source: Internet
Author: User

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

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.