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

[LeetCode 题解]:Convert Sorted List to Binary Search Tree

时间:2014-07-29 13:40:48      阅读:601      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   io   代码   div   

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

题意:给定一个有序的链表,将其转换成平衡二叉搜索树

思路: 二分法

要构建一个平衡二叉树,二分法无疑是合适的,至于如何分是的代码简洁,就需要用到递归了。

class Solution {
public:
    // find middle element of the list
    ListNode *getmiddleList(ListNode *left,ListNode *right){
        //omit the condition :  left!=right && left->next!=right
        ListNode *pre,*last;
        pre=left; last =left->next;
        while(last!=right){
            last = last->next;
            if(last!=right){
                last = last->next;
                pre=pre->next;
            }
        }
        return pre;
    }
    
    // retri-BST constructor
    TreeNode *getBST(ListNode *left,ListNode *right){
        TreeNode *root = new TreeNode(0);
        //no leaf 
        if(left==right) return NULL;
        // only one leaf
        if(left->next == right){
            root->val=left->val;
            return root;
        }
        //more than one leaf
        ListNode *middle =getmiddleList(left,right);
        root->val = middle->val;
        root->left = getBST(left, middle);
        root->right = getBST(middle->next,right);
        return root;
    }
    TreeNode *sortedListToBST(ListNode *head) {
        TreeNode* root= new TreeNode(0);
        if(head==NULL) return NULL;
        if(head->next==NULL){
            root->val=head->val;
            root->left=root->right=NULL;
            return root;
        }
        ListNode *left,*middle,*right;
        middle=left=head;
        right=head->next;
        while(right){
            right=right->next;
            if(right){
                right=right->next;
                middle=middle->next;
            }
        }
        root->val=middle->val;
        root->left = getBST(left, middle);
        root->right= getBST(middle->next,right);
        return root;
    }
};     

转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢!

[LeetCode 题解]:Convert Sorted List to Binary Search Tree,布布扣,bubuko.com

[LeetCode 题解]:Convert Sorted List to Binary Search Tree

标签:style   blog   http   color   strong   io   代码   div   

原文地址:http://www.cnblogs.com/double-win/p/3874950.html

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