[leetcode] 109. Convert Sorted List to Binary Search Tree

来源:互联网 发布:java获取list泛型类型 编辑:程序博客网 时间:2024/06/07 07:08

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

这道题是将已排序链表转化为高度平衡的二叉搜索树,题目难度为Medium。题目和108题(传送门)相关,感兴趣的同学可以先看下108题。

题目要求BST高度平衡,所以在转化链表某部分时要先找到该部分的中点,中点之前的节点组成左子树,中点之后的节点组成右子树,这样通过递归即可完成BST的生成。找链表中点可以用快慢指针法。具体代码:

class Solution {    TreeNode* genBST(ListNode *head, ListNode *tail) {        ListNode *fast = head;        ListNode *slow = head;        TreeNode *root = NULL;        if(!head || head == tail) return NULL;        while(fast != tail) {            if(fast->next == tail) break;            fast = fast->next->next;            slow = slow->next;        }        root = new TreeNode(slow->val);        root->left = genBST(head, slow);        root->right = genBST(slow->next, tail);        return root;    }public:    TreeNode *sortedListToBST(ListNode *head) {        return genBST(head, NULL);    }};

0 0