[leetcode] Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree

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

思路:

这个题目和将数组变成BST的很像,方法都一样,只是一个是数组的操作,一个是链表的操作。题外话,也是以后要注意的。开始认为这么做太费时间了,毕竟每次都要找中间节点,以为结果一定会TLE,所以没试。就看了别人写的,才发现这样可以。这题不算自己做出来的吧,以后不管怎样,都应该自己试试。

题解:

/**
 * 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:
    int listlen(ListNode *head) {
        int len = 1;
        while(head->next) {
            len++;
            head = head->next;
        }
        return len;
    }
    void CreateBST(TreeNode *&root, ListNode *head, int l, int r) {
        ListNode *p = head;
        if(l<=r) {
            int mid = (l+r)/2;
            for(int i=l;i<mid;i++) {
                p = p->next;
            }
            root = new TreeNode(p->val);
            CreateBST(root->left, head, l, mid-1);
            CreateBST(root->right, p->next, mid+1, r);
        }
    }
    TreeNode *sortedListToBST(ListNode *head) {
        TreeNode *root;
        if(head==NULL)
            return root;
        CreateBST(root, head, 0, listlen(head)-1);
        return root;
    }
};
View Code

 

posted on 2014-12-24 13:37  cha1992  阅读(101)  评论(0编辑  收藏  举报

导航