给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例一:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
法1:思路:直接将链表中的结点全部列入vector容器中,然后当作【简单】将有序数组转换为二叉搜索树///递归使用这题来做
TreeNode* sortedListToBST(ListNode* head) {
if (!head) return (TreeNode*)head;
vector<int> vec;
ListNode* p = head;
while (p)
{
vec.push_back(p -> val);
p = p -> next;
}
return convert(vec, 0, vec.size());
}
TreeNode* convert(vector<int>& nums, int start, int end)
{
if (start == end) return NULL;
int mid = start + (end - start) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root -> left = convert(nums, start, mid);
root -> right = convert(nums, mid + 1, end);
return root;
}
法2:还是递归的方法,不过不需要将指针上的值列入容器,而是直接运用递归回溯。注意while循环中的判断条件!
TreeNode* sortedListToBST(ListNode* head) {
return build_tree(head, NULL);
}
TreeNode* build_tree(ListNode* head, ListNode* tail)
{
if(!head) return NULL;
ListNode* pre = nullptr;
ListNode* slow = head;
ListNode* fast = head;
while (fast != NULL && fast -> next != NULL)
{
pre = slow;
slow = slow -> next;
fast = fast -> next -> next;
}
if(pre != NULL) pre -> next = NULL;
TreeNode* root = new TreeNode(slow -> val);
if(head == slow) return root;
root -> left = build_tree(head, pre);
root -> right = build_tree(slow -> next, tail);
return root;
}
总结:这题让我更加理解平衡二叉树,更觉得二叉树和递归密不可分。要一直判断一个结点的左右子树是否都平衡,递归确实是最好的方法。