[leetcode-109-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.
思路:利用快慢指针找到中间节点,作为根节点,然后左子树即为左边链表部分,右子树即为右边链表部分,递归进行即可。
TreeNode* sortedListToBST(ListNode* head) { //利用fast 和 slow 指针 找到链表中点 return build(head,NULL); } TreeNode* build(ListNode* start, ListNode* end) { if (start == end) { return NULL; } ListNode* fast = start; ListNode* slow = start; while (fast != end && fast->next != end)//注意第一次执行的时候end为NULL 没毛病。。 { fast = fast->next->next; slow = slow->next; } TreeNode* node = new TreeNode(slow->val); node->left = build(start, slow); node->right = build(slow->next, end); return node; }
参考: