首页 > 其他 > 详细

【leetcode】Convert Sorted List to Binary Search Tree

时间:2015-05-17 18:36:49      阅读:138      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!