109. Convert Sorted List to Binary Search Tree

每日一题 2019 - 04 - 25

题目:

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

1
2
3
4
5
6
7
8
9
Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

0
/ \
-3 9
/ /
-10 5

解法:

这个题让在给定的链表序列里面构造出一颗平衡二叉搜索树,也即每一颗子树的左右子树高度差不大于 1 ,由于给定的序列是排序好的序列,所以可以直接使用二分法来完成构建;

  • 每一次取出当前序列的中点,把当前序列的中点当做根节点,然后使用左右两边的序列对左右两边的子树进行构建;
  • 重复上述过程,直到左右两边的序列遍历完毕,即可完成任务;

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head == NULL)
{
return NULL;
}
vector<int> test ;
ListNode* temp = head;
while(temp)
{
test.push_back(temp->val);
temp = temp -> next ;
}
int mid = (0+test.size())/2 ;
TreeNode* node = new TreeNode(test[mid]);
node -> left = build(test,0,mid-1);
node -> right = build(test,mid+1,test.size()-1);
return node;
}
TreeNode* build(vector<int>& test,int start,int end)
{
if(start > end || start < 0 || end < 0 )
{
return NULL ;
}
if(start == end)
{
TreeNode* now = new TreeNode(test[start]);
return now ;
}
int mid = (start + end) /2 ;
TreeNode* now = new TreeNode(test[mid]);
now -> left = build(test,start,mid-1);
now -> right = build(test,mid+1,end);
return now ;
}
};
0%
undefined