109. Convert Sorted List to Binary Search Tree
难度: Middle
刷题内容
原题连接
- https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/
内容描述
``` 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9 / / -10 5 ```
解题方案
思路 1
1. 用快慢指针找链表中点
2. 断开前半部分和后半部分
3. 迭代构造左右子树
TreeNode* dfs(ListNode* node){
if(node == NULL)
return NULL;
if(node->next==NULL)
return new TreeNode(node->val);
ListNode* fast=node;
ListNode* slow=node;
ListNode* last = slow;
while(fast&&fast->next){
last = slow;
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
last->next = NULL;
TreeNode* root = new TreeNode(slow->val);
if (node != slow)
root->left=dfs(node);
root->right=dfs(fast);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
return dfs(head);
}