109. Convert Sorted List to Binary Search Tree
struct TreeNode* constr(struct ListNode* head,struct ListNode* tail)
{
if(head==tail) return NULL;
struct ListNode *mid=head,*temp=head;
while(temp!=tail&&temp->next!=tail)
{
temp=temp->next->next;
mid=mid->next;
}
struct TreeNode *T=(struct TreeNode*)malloc(sizeof(struct TreeNode));
T->val=mid->val;
T->left=constr(head,mid);
T->right=constr(mid->next,tail);
return T;
}
struct TreeNode* sortedListToBST(struct ListNode* head) {
struct TreeNode *root=constr(head,NULL);
return root;
}
本文介绍了一种将已排序的链表转换为平衡二叉搜索树的方法。通过递归地选择中间节点作为根节点,并继续对左右两部分进行相同操作来构建树。这种方法确保了树的高度尽可能低。
303

被折叠的 条评论
为什么被折叠?



