题目:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
由排序链表构造二叉树。根据数组构造二叉树的思想,想到对链表不断二分的方式完成功能。
TreeNode *sortedListToBST(ListNode *head)
{
TreeNode *root=NULL;
if(!head) return root;
if(!head->next) return root=new TreeNode(head->val);
ListNode *p=head, *q=head, *pre=NULL;
while(q&&q->next!=NULL) //下面是链表二分过程
{
q=q->next->next;
pre=p; //pre是用来后面断开链表的
p=p->next; //步长不同
}
pre->next=NULL; //断开链表
root=new TreeNode(p->val);
p=p->next; //构造了根节点,不能再用了
root->left=sortedListToBST(head);
root->right=sortedListToBST(p);
return root;
}
链表转平衡二叉树
本文介绍了一种将有序链表转换为高度平衡二叉搜索树的方法。通过递归地对链表进行二分,找到中间元素作为根节点,并以此构建左子树和右子树。
409

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



