Leetcode: 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.

分析:我们比较熟悉由一个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;
    }
};

 

posted on 2014-11-25 20:22  Ryan-Xing  阅读(149)  评论(0编辑  收藏  举报