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

怎样用前序与中序重建二叉树?

查看完整题解

参考回答

直接回答

假定键互异,前序首项为根。在中序里找到根,左段归左子树、右段归右子树。按各段大小继续分配前序位置,递归构建。

讲清原理

用映射保存中序位置,避免每一层线性寻找,预期时间 O(n)、映射空间 O(n),递归空间 O(h)。检查长度、重复键和根是否落在当前中序区间,拒绝不一致输入。

例子与易错点

前序 3、1、2,中序 1、2、3,可恢复根 3、左根 1、1 的右孩子 2。重复键时仅靠两条值序列通常不唯一,需要额外身份或形状信息。

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

static final class Node {
    int value;
    Node left;
    Node right;
    Node(int value) { this.value = value; }
}
static Node rebuild(int[] preorder, int[] inorder) {
    if (preorder.length != inorder.length) throw new IllegalArgumentException("length");
    var positions = new java.util.HashMap<Integer, Integer>();
    for (int i = 0; i < inorder.length; i++) {
        if (positions.put(inorder[i], i) != null) throw new IllegalArgumentException("duplicate");
    }
    int[] cursor = {0};
    Node root = rebuildPart(preorder, positions, cursor, 0, inorder.length);
    if (cursor[0] != preorder.length) throw new IllegalArgumentException("extra");
    return root;
}
static Node rebuildPart(int[] pre, java.util.Map<Integer, Integer> positions,
                        int[] cursor, int lo, int hi) {
    if (lo == hi) return null;
    if (cursor[0] >= pre.length) throw new IllegalArgumentException("truncated");
    int value = pre[cursor[0]++];
    Integer index = positions.get(value);
    if (index == null || index < lo || index >= hi) throw new IllegalArgumentException("inconsistent");
    Node node = new Node(value);
    node.left = rebuildPart(pre, positions, cursor, lo, index);
    node.right = rebuildPart(pre, positions, cursor, index + 1, hi);
    return node;
}

相关题:第 21 题、第 41 题、第 59 题。

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

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