给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9], 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5
方法一:将有序链表存入数组中,然后按照不断找中点,构建左右子树。
代码展示:
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
vector<int> vec;
while(head!=NULL){
vec.push_back(head->val);
head = head->next;
}
return createBST(vec,0,vec.size()-1);
}
TreeNode* createBST(vector<int>& vec,int left,int right){
if(left>right)
return NULL;
int mid = (1/2.0)*(left+right);
TreeNode* root = new TreeNode(vec[mid]);
root->left = createBST(vec,left,mid-1);
root->right = createBST(vec,mid+1,right);
return root;
}
};
方法二:利用fast、slow快慢指针,每次fast走两格,slow走一格,这样slow总会指向中点,然后分别构建左右子树。
代码展示:
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
return createBST(head,NULL);
}
TreeNode* createBST(ListNode* head,ListNode* tail){
if(head==tail)
return NULL;
ListNode* fast = head;
ListNode* slow = head;
while(fast!=tail){
fast = fast->next;
if(fast!=tail){
fast = fast->next;
slow = slow->next;
}
}
TreeNode* root = new TreeNode(slow->val);
root->left = createBST(head, slow);
root->right = createBST(slow->next,tail);
return root;
}
};