leetcode Convert Sorted List to Binary Search Tree

class Solution {
public:
    int calLen(ListNode *node)
    {
        int len = 0;
        while(node)
        {
            len++;
            node = node->next;
        }
        return len;
    } 
    TreeNode *createTree(ListNode *node, int left, int right)
    {
        if (left > right)
            return NULL;         
        int mid = (left + right) / 2;       
        ListNode *p = node;        
        for(int i = left; i < mid; i++)
            p = p->next;            
        TreeNode *leftNode = createTree(node, left, mid - 1);
        TreeNode *rightNode = createTree(p->next, mid + 1, right);       
        TreeNode *tNode = new TreeNode(p->val);       
        tNode->left = leftNode;
        tNode->right = rightNode;        
        return tNode;        
    }
    
    TreeNode *sortedListToBST(ListNode *head) {
        int len = calLen(head);
        return createTree(head, 0, len - 1);
    }
};

 

 

posted @ 2013-09-05 18:42  代码改变未来  阅读(280)  评论(0编辑  收藏  举报