将一个有序的链表转化为一个二叉搜索树

题目:

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

解题思路:

解决这道题目,首先要想到的就是二叉树是递归定义的。所以我们在将链表转化为二叉树时,就要先从递归的角度入手。

我们知道二叉搜索树是根节点比左子树的所有节点大,比右子树的所有节点小。再次,平衡二叉树的左右子树高度差不超过1.所以,我们可以找到链表的中间节点作为整个子树的根节点,在递归的找左子树的根节点和右子树的根节点。这样转化后的二叉树就是一个平衡的二叉搜索树。

代码实现:

/**
 * 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) {
        return ListToBST(head, NULL);
    }
    TreeNode* ListToBST(ListNode* head, ListNode* tail)
    {
        //根据先序遍历的方式建立二叉树,
        if(head == tail)
            return NULL;
        //由于这是一个排好序的链表,所以中间节点就是BST的根节点
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast != tail && fast->next != tail)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        TreeNode* root = new TreeNode(slow->val);
        //按照递归的方式建立左子树,右子树
        root->left = ListToBST(head, slow);
        root->right = ListToBST(slow->next, tail);
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_40417029/article/details/80975429