与上一题相同。

 

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

  

posted on 2013-04-15 03:22  tanghulu321  阅读(99)  评论(0编辑  收藏  举报