将一个已排序的链表或数组转化成一棵平衡二叉树

Problem:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

解题思路:这里要充分利用元素的有序性,来构造一棵平衡二叉树,这样可以避免为了维持二叉树的平衡性,而进行各种旋转操作。可以每次都向树中插入一个序列中的中间元素,这样就可以保证该结点的左子树和右子树含有结点的数目相等(或只相差一个)。这样反复操作,就可以构造一颗类完全二叉树,肯定满足平衡二叉树的条件。

代码实现如下:

class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        if(head == NULL)
            return NULL;
        ListNode* end;//尾结点
        TreeNode* root;//平衡二叉树根结点
        end = head;
        while(end->next)
            end = end->next;
        root = CreateAVLTree(head, end);

        return root;
    }

    TreeNode* CreateAVLTree(ListNode* head, ListNode* end)
    {
        TreeNode *root;//构造树结点
        ListNode *slow, *fast;//用于查找中间结点
        ListNode *newEnd;//构建新的尾结点
        newEnd = slow = fast = head;

        if(head == end)//链表只有一个结点
        {
            root = new TreeNode(head->val);
            return root;
        }
        while(fast != end && fast->next != end)//查找链表的中间结点
        {
            newEnd = slow;
            slow = slow->next;
            fast = fast->next->next;
        }

        root = new TreeNode(slow->val);
        if(newEnd != slow)
            root->left = CreateAVLTree(head, newEnd);
        root->right = CreateAVLTree(slow->next, end);

        return root;
    }
};

Problem:Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

思路和上面完全一样,代码实现如下所示:

class Solution {
public:
    TreeNode *sortedArrayToBST(vector<int> &num) {
        TreeNode *root = NULL;
        if(!num.size())
            return NULL;
        int head, end;//处理数组元素的指针
        head = 0;
        end = num.size() - 1;
        root = CreateAVLTree(num, head, end);

        return root;
    }

    TreeNode *CreateAVLTree(vector<int> &num, int head, int end)
    {
        TreeNode *root;
        int middle = (head + end)/2;
        if(head == end)//只有一个元素
        {
            root = new TreeNode(num[head]);
            return root;
        }
        root = new TreeNode(num[middle]);
        if(middle != head)//容器内只有两个元素
            root->left = CreateAVLTree(num, head, middle-1);
        root->right = CreateAVLTree(num, middle+1, end);

        return root;
    }
};

将一个已排序的链表或数组转化成一棵平衡二叉树

时间: 2024-07-31 20:35:18

将一个已排序的链表或数组转化成一棵平衡二叉树的相关文章

[Leetcode] Merge k sorted lists 合并k个已排序的链表

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 思路:这题最容易想到的是,(假设有k个链表)链表1.2合并,然后其结果12和3合并,以此类推,最后是123--k-1和k合并.至于两链表合并的过程见merge two sorted lists的分析.复杂度的分析见JustDoIT的博客.算法复杂度:假设每个链表的平均长度是n,则1.2合并,遍历2n个

[Leetcode] Remove duplicate from sorted list ii 从已排序的链表中删除重复结点

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example,Given1->2->3->3->4->4->5, return1->2->5.Given1->1->1->2->3, return2->3. 这题和R

leetcode 题解:Search in Rotated Sorted Array II (旋转已排序数组查找2)

题目: Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a function to determine if a given target is in the array. 说明: 1)和1比只是有重复的数字,整体仍采用二分查找 2)方法二 : 实现:  

在已排序好的数组找两个数a加b等于给定的N

public class 在已排序好的数组找两个数a加b等于给定的N { public static void main(String[] args) { /** * 初始化参数 Result为结果值 * num 是测试数组 * start 开始游标, end 结束游标 */ int Result = 15; int[] num = {1,2,4,7,11,15}; int start = 0, end = num.length-1; //从数组的两端开始扫,若两数之和小于目标,则头往后进一位,

循环链表(2) - 插入节点至已排序链表

编写一个程序,在一个已排序的循环链表中插入一个新的节点. 例如,假设初始的循环链表如下所示: 插入新的节点7之后,上面的循环链表变为了下面所示: 算法: 假设需要插入的新节点为newNode, 则插入操作可以分为下面的3种情形: 1) 链表为空: a) 因为循环链表只有newNode这一个节点,则自我循环. newNode->next = newNode; b) 调整头指针 *head = newNode; 2) 新节点需要插入到链表头节点的前面: (a) 遍历链表,找出尾节点. while(c

剑指Offer15 合并两个已排序链表

1 /************************************************************************* 2 > File Name: 15_MergeTwoSortList.cpp 3 > Author: Juntaran 4 > Mail: [email protected] 5 > Created Time: 2016年08月30日 星期二 15时49分47秒 6 ********************************

leetcode 题解:Merge Sorted Array(两个已排序数组归并)

题目: Given two sorted integer arrays A and B, merge B into A as one sorted array. Note:You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B ar

leetcode 题解:Remove Duplicates from Sorted Array II(已排序数组去三次及以上重复元素)

题目: Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 说明: 1)设个标志可实现 实现: 1 class Solution { 2 public

leetcode 题解:Remove Duplicates from Sorted Array(已排序数组去重)

题目: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example,Given input array A