给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9], 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5
思路:将链表中的元素存放在vector中,然后从用l,r来表示每棵子树在vector的所有节点,每次取中间的节点作为子树的根节点,这样子使得左右子树节点相等,即可构建高度平衡的二叉树.
/**
* 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) {
vector<int> v;
ListNode* cur=head;
while(cur!=NULL){
v.push_back(cur->val);
cur=cur->next;
}
TreeNode* root=buildBST(v,0,v.size()-1);
return root;
}
TreeNode* buildBST(vector<int>& nums,int l,int r){
if(l>r) return NULL;
int mid=(l+r)/2;
auto node= new TreeNode(nums[mid]);
node->left=buildBST(nums,l,mid-1);
node->right=buildBST(nums,mid+1,r);
return node;
}
};