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

109. Convert Sorted List to Binary Search Tree

时间:2016-06-22 15:48:46      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

Given a singly linked list where elements are sorted in ascending order,

convert it to a height balanced BST.

==============

题目:将升序的链表,转化为BST(note:此BST要求是高度平衡,就是树种左右子树高度差不超过1)

思路:

def TreeNode* sortedListToBST(ListNode* head){

    按照slow/fast方式找到链表的中间节点mid,

    将升序链表在mid节点处切割成为两个链表head1,和head2

    将中间节点的值,new一个新的TreeNode节点:TreeNode *root = new TreeNode(head2->val)

    下面开始递归:
        root的左子树就是sortedListToBST(head1)
        root的右子树就是sortedListToBST(head2->next)
    return root
}

代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * 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==nullptr){
            return nullptr;
        }else if(head->next==nullptr){
            return new TreeNode(head->val);
        }

        ListNode *slow,*fast,*prev;
        slow = fast = head;
        prev = nullptr;
        while(fast && fast->next){
            prev = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        prev->next = nullptr;
        //showList(head);
        //showList(slow);
        TreeNode *root = new TreeNode(slow->val);
        root->left = sortedListToBST(head);
        root->right = sortedListToBST(slow->next);
        return root;
    }
};

 

109. Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/li-daphne/p/5606989.html

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