Leetcode Convert Sorted List to Binary Search Tree

来源:互联网 发布:淘宝提示自助开通 编辑:程序博客网 时间:2024/05/18 14:13
/** * 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* build(ListNode *head,int n)    {        if(n==0)return NULL;        if(n==1)return new TreeNode(head->val);        int i=0;        int m = n/2;        ListNode *h = head;        while(i<m)        {            h=h->next;            i++;        }        TreeNode *res = new TreeNode(h->val);        res->left = build(head,m);        if(n%2==0)res->right = build(h->next,m-1);        else res->right = build(h->next,m);        return res;    }    TreeNode *sortedListToBST(ListNode *head) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int n=0;        ListNode *h = head;        while(h!=NULL)        {            n++;            h=h->next;        }        return build(head,n);    }};

原创粉丝点击