题目描述:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
与运用有序数组构造BST类似,但是确定中点需要利用快慢指针遍历才可以。
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head==NULL) return NULL;
if(head->next==NULL)
{
TreeNode* root=new TreeNode(head->val);
return root;
}
ListNode* p=head;
ListNode* q=head;
ListNode* pre_p=new ListNode(0);
pre_p->next=p;
while(q!=NULL&&q->next!=NULL)
{
pre_p=p;
q=q->next->next;
p=p->next;
}
pre_p->next=NULL;
TreeNode* left=sortedListToBST(head);
TreeNode* right=sortedListToBST(p->next);
TreeNode* root=new TreeNode(p->val);
root->left=left;
root->right=right;
return root;
}
};
本文介绍了一种将有序链表转换为高度平衡二叉搜索树的方法。通过使用快慢指针找到链表中点作为根节点,并递归地构造左右子树,最终形成一棵平衡的二叉搜索树。
411

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



