给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9], 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5
解题思路:
原本打算在链表上直接操作,但是想想很麻烦,题目对空间也没限制。于是想到把链表节点的值先拷贝到vector中,然后构建二叉搜索树。
以题给的有序链表为例,其中点为0,[-10, -3, 0, 5, 9],每次以中点为根节点,以中点为界,将原来的vector划分为左右两个部分,
l=[-10, -3],r=[5, 9],然后递归的构造根节点的左右孩子即可。
代码如下:
/**
* 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 {
private:
TreeNode* helper(vector<int> input)
{
if(input.empty())
return nullptr;
if(input.size()==1)
{
TreeNode *root=new TreeNode(input[0]);
return root;
}
int mid=input.size()/2;
TreeNode *root=new TreeNode(input[mid]);
vector<int> l,r;//以下为划分vector的过程,要注意,vector的assign操作是左闭右开的
l.assign(input.begin(),input.begin()+mid);
r.assign(input.begin()+mid+1,input.end());
root->left=helper(l);
root->right=helper(r);
return root;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head==nullptr)
return nullptr;
TreeNode* root=new TreeNode(head->val);
if(head->next==nullptr)
return root;
//只需要链表中节点的值,在链表本身操作比较麻烦,所以先把链表节点值拷贝到vector中
vector<int> list_vals;
while(head){
list_vals.push_back(head->val);
head=head->next;
}
root=helper(list_vals);//运行至此说明链表中至少有两个节点
return root;
}
};