码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Convert Sorted List to Binary Search Tree

时间:2015-05-17 18:38:05      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

【leetcode】Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4510067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!