Convert Sorted List to Binary Search Tree

来源:互联网 发布:淘宝千人千面怎么用 编辑:程序博客网 时间:2024/06/14 03:31

Convert Sorted List to Binary Search Tree

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

Subscribe to see which companies asked this question.


解析:

一下居然过了,递归调用,函数参数为链表的起始地址与长度。

代码:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* sortedListToBST(ListNode* head) {                int listlen=0;        ListNode* ll=head;        while(ll)        {            listlen++;            ll=ll->next;        }        return conv(head,listlen);                    }        TreeNode* conv(ListNode* list,int len)    {        if (len==0) return NULL;        ListNode* right=list;        int rightlen=len/2;        while(rightlen--)        {            right=right->next;        }        TreeNode *root=new TreeNode(right->val);        right=right->next;        root->right=conv(right,len-(len/2+1));        root->left=conv(list,len/2);        return root;            }    };



0 0
原创粉丝点击