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

来源:互联网 发布:搁置争议 共同开发知乎 编辑:程序博客网 时间:2024/06/07 06:29

题目:

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

程序:

class Solution {public:    TreeNode *sortedListToBST(ListNode *head) {        return BST(head,NULL);    }    TreeNode *BST(ListNode *head,ListNode *tail)    {        if(head == tail)            return NULL;        ListNode *s = head;        ListNode *f = head;        while(f!=tail && f->next!=tail)        {            s = s->next;            f = f->next->next;        }        TreeNode *root = new TreeNode(s->val);        root->left = BST(head,s);        root->right = BST(s->next,tail);        return root;    }};
原创粉丝点击