109. 有序链表转换二叉搜索树
题目描述
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
解
二叉搜索树左右平衡,那么根节点就是数组的中位数。递归得到左右子树即可。懒得操作链表转换成数组就简单了。
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head)return nullptr;
vector<int> nodes;
while(head)
{
nodes.emplace_back(head->val);
head=head->next;
}
return genBST(nodes,0,nodes.size());
}
TreeNode* genBST(vector<int>& nodes,int st,int ed)
{
if(st>=ed)return nullptr;
int mid=st+(ed-st)/2;
TreeNode* root = new TreeNode(nodes[mid]);
root->left= genBST(nodes,st,mid);
root->right= genBST(nodes,mid+1,ed);
return root;
}
};