Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
if (!head) {
return NULL;
}
ListNode *end = head;
while (end->next) {
end = end->next;
}
return build(head, end);
}
TreeNode *build(ListNode *begin, ListNode *end) {
if (!begin){
return NULL;
}
if (!begin->next) {
TreeNode *root = new TreeNode(begin->val);
return root;
}
ListNode dummy(-1);
dummy.next = begin;
auto slow = &dummy;
auto fast = begin;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
TreeNode *root = new TreeNode(slow->next->val);
auto head = slow->next->next;
slow->next = NULL;
root->left = build(begin, slow);
root->right = build(head, end);
return root;
}
};
本文介绍了一种将升序排列的单链表转换为高度平衡的二叉搜索树的方法。通过递归地选择中间节点作为根节点,并以此为基础构建左子树和右子树,确保了树的高度平衡。
236

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



