1 Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
排序链表转换成平衡二叉搜索树
二叉搜索树就是左小右大,平衡树就是高度差小于等于1.可以想到根节点root一定是链表中间节点,左半部分又是一颗平衡二叉搜索树,则root->left就是左部分的中间节点,同时是左半部分的root,右边同理。
/**
* 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) {
return ToBST(head,nullptr);
}
TreeNode* ToBST(ListNode* head, ListNode* end){
if(head==end) return nullptr;
if(head->next==end){
TreeNode* root=new TreeNode(head->val);
return root;
}
ListNode* mid=head;
ListNode* temp=head;
while(temp!=end&&temp->next!=end){
mid=mid->next;
temp=temp->next->next;
}//中间节点
TreeNode* root=new TreeNode(mid->val);
root->left=ToBST(head,mid);
root->right=ToBST(mid->next,end);
return root;
}
};