题目描述
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
白话题目:
算法:
详细解释关注 B站 【C语言全代码】学渣带你刷Leetcode 不走丢 https://www.bilibili.com/video/BV1C7411y7gB
C语言完全代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
static struct TreeNode* dfs(struct ListNode* head, struct ListNode* tail)
{
if (head == tail)
{
return NULL;
}
// 找中点
struct ListNode* fast = head;
struct ListNode* slow = head;
while (fast != tail && fast->next != tail)
{
fast = fast->next->next;
slow = slow->next;
}
// 创建树
struct TreeNode* pNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
pNode->val = slow->val;
pNode->left = dfs(head, slow); // 左闭右开
pNode->right = dfs(slow->next, tail);
return pNode;
}
struct TreeNode* sortedListToBST(struct ListNode* head){
if (NULL == head)
{
return NULL;
}
return dfs(head, NULL);
}