• 7. 重建二叉树


    本文章引自CyC2018/CS-Notes,欢迎大家移步欣赏!

    7. 重建二叉树

    题目链接

    牛客网

    题目描述

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


    解题思路

    前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。然后分别对左右子树递归地求解。


    // 缓存中序遍历数组每个值对应的索引
    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.val);
        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;
    }
    
    我的个人博客 Ahoh(www.ahoh.club),找我一起玩耍吧!!
  • 相关阅读:
    javascript数组
    Javascript prototype理解
    Javascript中的类的创建
    Div拖动效果
    javascript, position
    getSelection();
    网页的宽和高
    javascript apply & call
    Hibernate数据丢失更新问题及解决 凡人
    招聘软件/网页UI设计师
  • 原文地址:https://www.cnblogs.com/weidawang/p/15413930.html
Copyright © 2020-2023  润新知