題目描述
給定一個單鏈表,其中的元素按升序排序,將其轉換爲高度平衡的二叉搜索樹。
本題中,一個高度平衡二叉樹是指一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 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);
}