zoukankan      html  css  js  c++  java
  • 算法题:5、重建二叉树

    题目描述

    根据二叉树的前序遍历和中序遍历的结构,重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不包含重复的数字

    解题思路

    前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分分为树的左子树中序遍历结果,右部分为树的右子树中序遍历结果。

    代码

    static class TreeNode {
        private Integer value;
        private TreeNode left;
        private TreeNode right;
    
        public TreeNode(Integer value) {
            this.value = value;
        }
    
        public TreeNode() {
        }
    }
    
    // 缓存中序遍历数组每个值对应的索引
    private Map<Integer, Integer> indexForInOrders = new HashMap<>();
    
    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        for (int i = 0; i < in.length; i++) {
            indexForInOrders.put(in[i], i);
        }
        return reConstructBinaryTree(pre, 0, pre.length - 1, 0);
    }
    
    private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int inL) {
        if (preL > preR) {
            return null;
        }
        TreeNode root = new TreeNode(pre[preL]);
        int inIndex = indexForInOrders.get(root.value);
        int leftTreeSize = inIndex - inL;
        root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, inL);
        root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, inL + leftTreeSize + 1);
        return root;
    }
    
  • 相关阅读:
    普通锁和分布式锁
    java 正则表达式
    java 字符串转date 格式转换
    消息中间件 kafka
    数据的存储方式:对象存储、文件存储、块存储
    Exceptional Control Flow(6)
    Exceptional Control Flow(5)
    Exceptional Control Flow(4)
    Exceptional Control Flow(3)
    Exceptional Control Flow(2)
  • 原文地址:https://www.cnblogs.com/fcb-it/p/12820347.html
Copyright © 2011-2022 走看看