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

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;
    }
};


    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/wan_hust/article/details/25877447
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞