首页 > 其他 > 详细

Leetcode: Convert Sorted List to Binary Search Tree

时间:2014-11-25 23:00:06      阅读:249      评论:0      收藏:0      [点我收藏+]

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

分析:我们比较熟悉由一个sorted array生成一个BST,不同的是这里的数据结构换为了linked list。我们同样可以用递归的方法生成BST,与数组不同的是我们需要先确定linked list的中间结点。

class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        if(head == NULL) return NULL;
        if(head->next == NULL){
            TreeNode *root = new TreeNode(head->val);
            return root;
        }
        //get length
        int n = 0;
        for(ListNode *p = head; p; p = p->next)
            n++;
        //find middle point
        ListNode *prev = NULL, *mid = head;
        for(int i = 0; i < (n-1)/2; i++){
            prev = mid;
            mid = mid->next;
        }
        TreeNode *root = new TreeNode(mid->val);
        if(prev)
            prev->next = NULL;
        if(mid != head)
            root->left = sortedListToBST(head);
        root->right = sortedListToBST(mid->next);
        return root;
    }
};

 

Leetcode: Convert Sorted List to Binary Search Tree

原文:http://www.cnblogs.com/Kai-Xing/p/4121848.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!