您的位置:首页 > 其它

[leetcode] 109.Convert Sorted List to Binary Search Tree

2015-07-01 10:33 337 查看
题目:

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

题意:

给定一个单链表,单链表的元素有序递增,转化为一颗高度平衡的二叉搜索树。

思路:

这道题只需要将这个单链表转化为一个数组,然后使用108题的代码即可。

代码如下:

/**
* 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> nums;
while(head != NULL){
nums.push_back(head->val);
head = head->next;
}
return buildBST(nums,0,nums.size() - 1);
}
TreeNode* buildBST(vector<int>& nums,int start,int end) {
if(start > end)return NULL;
int index = (start + end)/2;
TreeNode* root = new TreeNode(nums[index]);
root->left = buildBST(nums,start,index - 1);
root->right = buildBST(nums,index + 1, end);
return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: