积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};

 

posted on 2016-06-22 14:26  x7b5g  阅读(197)  评论(0编辑  收藏  举报