[LeetCode] Convert Sorted List to Binary Search Tree

来源:互联网 发布:ubuntu 16.10安装lamp 编辑:程序博客网 时间:2024/06/07 03:21
[Problem]
Given a singly linked list where elements are sorted in ascendingorder, convert it to a height balanced BST.

[Analysis]

和 Convert Sorted Array to Binary Search Tree差不多,将链表中的数值用一个vector存就转换成上一题了。

[Solution]

//
// Definition for singly-linked list.
// struct ListNode {
// int val;
// ListNode *next;
// ListNode(int x) : val(x), next(NULL) {}
// };
//
//
// Definition for binary tree
// struct TreeNode {
// int val;
// TreeNode *left;
// TreeNode *right;
// TreeNode(int x) : val(x), left(NULL), right(NULL) {}
// };
//
class Solution {
public:
// build tree
TreeNode *build(vector &num, int begin, int end){
if(begin > end){
return NULL;
}

// build left brunch and right brunch
int mid = (begin+end)/2;
TreeNode* left = build(num, begin, mid-1);
TreeNode* right = build(num, mid+1, end);

// build tree
TreeNode* node = new TreeNode(num[mid]);
node->left = left;
node->right = right;
return node;
}

// sorted array to BST
TreeNode *sortedArrayToBST(vector &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(num.size() == 0){
return NULL;
}
else{
return build(num, 0, num.size()-1);
}
}

// sorted list to BST
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector array;
while(head != NULL){
array.push_back(head->val);
head = head->next;
}
return sortedArrayToBST(array);
}
};
说明:版权所有,转载请注明出处。Coder007的博客
阅读全文
0 0