Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎样把有序链表建成平衡 BST?

查看完整题解

参考回答

直接回答

先求链表长度,再按中序次序构建。递归先为左半数量建左子树,当前游标节点作根并向后移动,再建右子树。这样不必每层寻找链表中点。

讲清原理

链表必须无环且严格递增。求长度和建树共 O(n),递归深度 O(log n),返回的树节点另外占 O(n)。若每次用快慢指针切中点,常见实现时间为 O(n log n)。

例子与易错点

原链表游标从头只向前走,每个元素恰好作一次根。用局部游标容器或明确返回状态,避免把全局字段留到下一次调用。对 AVL 元数据的要求与数组版本相同。

下面是 Java 21 类成员片段,可放入同一个工具类。

static final class Node {
    int value;
    Node left;
    Node right;
    Node(int value) { this.value = value; }
}
static final class Link {
    int value;
    Link next;
    Link(int value) { this.value = value; }
}

static final class Cursor {
    Link current;
    Cursor(Link head) { current = head; }
}
static Node fromSortedList(Link head) {
    int size = 0;
    for (Link p = head; p != null; p = p.next) {
        if (p.next != null && p.value >= p.next.value) throw new IllegalArgumentException("strict order");
        size++;
    }
    return fromCount(new Cursor(head), size);
}
static Node fromCount(Cursor cursor, int size) {
    if (size == 0) return null;
    Node left = fromCount(cursor, size / 2);
    Node root = new Node(cursor.current.value);
    cursor.current = cursor.current.next;
    root.left = left;
    root.right = fromCount(cursor, size - size / 2 - 1);
    return root;
}

相关题:第 59 题、第 70 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。