码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Convert Sorted List to Binary Search Tree

时间:2014-10-30 10:55:20      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   for   sp   strong   

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.

 

为了满足平衡要求,容易想到提出中间节点作为树根,因为已排序,所以左右两侧天然满足BST的要求。

左右子串分别递归下去,上层根节点连接下层根节点即可完成。

详见代码与注释。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        if(head == NULL)
        {//
            return NULL;
        }
        else if(head->next == NULL)
        {//一个节点
            TreeNode* root = new TreeNode(head->val);
            return root;
        }
        else
        {
            ListNode* mid = findMid(head);  //找出中间节点作为根节点(满足保持平衡的要求)
            ListNode* lefthead = head;      //左子串头节点为原链表头节点
            ListNode* righthead = mid->next;//右子串头节点为中间节点的下一个节点
            TreeNode* root = new TreeNode(mid->val);    //递归下去即可
            root->left = sortedListToBST(lefthead);
            root->right = sortedListToBST(righthead);
            return root;
        }
    }

    ListNode* findMid(ListNode* head)
    {//调用前提是head != NULL
     //若链表为偶数,则返回均分后半子串的指针;若链表为奇数,则返回中间节点的指针
        ListNode* pre = NULL;
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast != NULL)
        {
            fast = fast->next;
            if(fast != NULL)
            {
                fast = fast->next;
                pre = slow;
                slow = slow->next;
            }
        }
        pre->next = NULL;   //前子串尾部置空
        return slow;
    }
};

bubuko.com,布布扣

【LeetCode】Convert Sorted List to Binary Search Tree

标签:style   blog   http   io   color   ar   for   sp   strong   

原文地址:http://www.cnblogs.com/ganganloveu/p/4061909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!