升序链表转换成二叉搜索树(BST)

题目描述

给定一个按升序排序的单链列表,将其转换为高度平衡的BST。

解题思路

关键点:二叉搜索树的中序遍历是升序的

(1)快慢指针找到链表中点,作为根节点

(2)递归链表的左半部分为左子树

(3)递归链表的右半部分为右子树

代码示例

class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        return sortedList(head, NULL);
    }
    TreeNode *sortedList(ListNode *head, ListNode *tail) {
        if (head == tail) return NULL;
        ListNode *p = head;
        ListNode *q = head;
        while (q != tail && q->next != tail) {//快慢指针找到链表中点
            p = p->next;
            q = q->next->next;
        }
        TreeNode *root = new TreeNode(p->val);//作为根节点
        root->left = sortedList(head, p);//递归链表的左半部分为左子树
        root->right = sortedList(p->next, tail);//递归链表的右半部分为右子树
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/summer00072/article/details/80922078