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

LeetCode Convert Sorted List to Binary Search Tree

时间:2014-12-13 13:21:52      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced 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 *getbTree(ListNode *head,int start,int end)
    {
        if(start<=end)
        {
            int mid = (start+end)>>1;
            ListNode *work = head;
            ListNode *rstart=NULL;
            for(int i=start;i<mid;i++)
            {
                work = work->next;
            }
            rstart = work->next;
            TreeNode *node = new TreeNode(work->val);
            node->left = getbTree(head,start,mid-1);
            node->right = getbTree(rstart,mid+1,end);
            return node;
        }
        else
            return NULL;
    }
    TreeNode *sortedListToBST(ListNode *head) {
        if(head==NULL)return NULL;
        int len = 0;
        ListNode *p = head;
        while(p)
        {
            ++len;
            p=p->next;
        }

        return getbTree(head,0,len-1);

    }
};

 

LeetCode Convert Sorted List to Binary Search Tree

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/55open/p/4161174.html

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