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

leetcode 109. Convert Sorted List to Binary Search Tree

时间:2015-02-16 11:37:14      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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

[Solution]

 1 TreeNode *sortedListToBST(ListNode *head) 
 2     {
 3         int len = 0;
 4         for (ListNode *visit = head; visit != NULL; visit = visit->next)
 5             len++;
 6         
 7         return BSTtranslate(head, 0, len - 1);
 8     }
 9     
10     TreeNode *BSTtranslate(ListNode *head, int left, int right)
11     {
12         if (left > right)
13             return NULL;
14             
15         int middle = (left + right) / 2;
16         ListNode *visit = head;
17         for (int i = left; i < middle; i++)
18             visit = visit->next;
19             
20         TreeNode *root = new TreeNode(visit->val);
21         root->left = BSTtranslate(head, left, middle - 1);
22         root->right = BSTtranslate(visit->next, middle + 1, right);
23         
24         return root;
25     }

 

leetcode 109. Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4293776.html

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