剑指Offer(4) — 重建二叉树|Java 刷题打卡

本文正在参加「Java主题月 – Java 刷题打卡」,详情查看活动链接

一、题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

二、思路分析

我们看上面的图片,首先数据保证了正确性,那么前序的第一个肯定是root节点,也就是1,那么我们需要在中序遍历中找到1的位置,左边就是这个root的左子树,右边就是root的右子树。

我们可以举个栗子:对根节点的左子树进行解析:

对右子树进行解析:

只需要不断递归即可,当边界左边大于右边的时候,则停止。

三、AC代码

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        if (pre == null || pre.length == 0 || in == null || in.length == 0) {
            return null;
        }
        TreeNode root = constructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length-1);
        return root;
    }

    TreeNode constructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) {
        // 不符合条件直接返回null
        if (startPre > endPre || startIn > endIn) {
            return null;
        }
        // 构建根节点
        TreeNode root = new TreeNode(pre[startPre]);
        for (int index = startIn; index <= endIn; index++) {
            if (in[index] == pre[startPre]) {
                // 左子树
                root.left = constructBinaryTree(pre, startPre + 1, startPre + (index - startIn), in, startIn, index - 1);
                // 右子树
                root.right = constructBinaryTree(pre, (index - startIn) + startPre + 1, endPre, in, index + 1, endIn);
                break;
            }
        }
        return root;
    }
}
复制代码

总结

将问题定义概括,是一种比较重要的能力。比如本题中,利用前序遍历,我们首先可以知道的是根节点,然后剩下的是左右节点的集合。但是,利用根节点,我们要是在中序遍历中,查找出它的位置,就可以以他为分割,左边是它的左子树,右边是其右子树。
关于这个节点的左右子树已经明确了,剩下的就是对左右子树的确定,也就是子问题的求解,其过程和根节点的一样。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享