convert-sorted-list-to-binary-search-tree

来源:互联网 发布:淘宝老客户刷销量 编辑:程序博客网 时间:2024/06/16 22:41

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode *sortedListToBST(ListNode *head) {        if(head==NULL)            return NULL;        return recurbuild(head);    }    TreeNode *recurbuild(ListNode* head)        {        if(head==NULL)            return NULL;        if(head->next==NULL)            {            return new TreeNode(head->val);        }        ListNode* sav=head;        ListNode* mid=head;        ListNode* pre=mid;        while(head&&head->next)            {            head=head->next->next;            pre=mid;            mid=mid->next;        }        pre->next=NULL;        TreeNode* temp=new TreeNode(mid->val);        temp->left=sortedListToBST(sav);        temp->right=sortedListToBST(mid->next);        return temp;    }};
0 0