首页 > 其他 > 详细

Convert Sorted List to Binary Search Tree

时间:2014-04-07 17:41:23      阅读:483      评论:0      收藏:0      [点我收藏+]

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

Solution: Recursion. Pre-order. O(n)

bubuko.com,布布扣
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 /**
10  * Definition for binary tree
11  * struct TreeNode {
12  *     int val;
13  *     TreeNode *left;
14  *     TreeNode *right;
15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
16  * };
17  */
18 class Solution {
19 public:
20     TreeNode *sortedListToBST(ListNode *head) {
21         return sortedListToBSTRe(head, getLength(head));
22     }
23     
24     TreeNode* sortedListToBSTRe(ListNode* &head, int length)
25     {
26         if(length == 0) return NULL;
27         int mid = length / 2;
28         TreeNode* left = sortedListToBSTRe(head, mid);
29         TreeNode* root = new TreeNode(head->val);
30         TreeNode* right = sortedListToBSTRe(head->next, length - mid - 1);
31         root->left = left;
32         root->right = right;
33         head = head->next;
34         return root;
35     }
36     
37     int getLength(ListNode* head) 
38     {
39         int length = 0;
40         while(head) {
41             length++;
42             head = head->next;
43         }
44         return length;
45     }
46 };
bubuko.com,布布扣

 

Convert Sorted List to Binary Search Tree,布布扣,bubuko.com

Convert Sorted List to Binary Search Tree

原文:http://www.cnblogs.com/zhengjiankang/p/3646978.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!