LeetCode | Convert Sorted List to Binary Search Tree

https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/

  1. 先找到链表中间节点的前一个节点(注意建dummy node)
  2. 存下中间节点,根据中间节点的值new出树的根节点
  3. 切开链表,分别对中间节点的左半部分和右半部分构造BST,最后将它们连到根节点上。

C++

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if (!head) return NULL;
        if (!head->next) return new TreeNode(head->val);
        
        ListNode dummy(0); dummy.next = head;
        ListNode *mid_prev = find_mid(&dummy);
        ListNode *mid = mid_prev->next;
        TreeNode *root = new TreeNode(mid->val);
        mid_prev->next = NULL;
        
        root->left = sortedListToBST(head);
        root->right = sortedListToBST(mid->next);
        
        return root;
    }
    
    ListNode* find_mid(ListNode* head) {
        ListNode *slow = head, *fast = head->next;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};
posted @ 2017-02-10 21:06  mioopoi  阅读(106)  评论(0编辑  收藏  举报