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

 

 1 class Solution {
 2 public:
 3     int listlen(ListNode * node)
 4     {
 5         int len=0;
 6         while(node)
 7         {
 8             ++len;
 9             node=node->next;
10         }
11         return len;
12     }
13 
14     TreeNode * createBST(ListNode *node,int left,int right)
15     {
16         if(left>right) return NULL;
17 
18         int mid=(left+right)/2;
19 
20         ListNode *p=node;
21 
22         for(int i=left;i<mid;i++)
23             p=p->next;
24 
25         TreeNode *leftNode=createBST(node,left,mid-1);
26         TreeNode *rightNode=createBST(p->next,mid+1,right);
27 
28         TreeNode *root=new TreeNode(p->val);
29         root->left=leftNode;
30         root->right=rightNode;
31 
32         return root;
33     }
34 
35     TreeNode* sortedListToBST(ListNode* head) {
36         int len=listlen(head);
37         return createBST(head,0,len-1);
38     }
39 };

 

posted on 2015-05-17 17:13  黄瓜小肥皂  阅读(119)  评论(0编辑  收藏  举报