zoukankan      html  css  js  c++  java
  • LeetCode-面试题07-重建二叉树

    来源:力扣(LeetCode)- 面试题07

    问题

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

    例如,给出

    前序遍历 preorder = [3,9,20,15,7]
    中序遍历 inorder = [9,3,15,20,7]
    返回如下的二叉树:

        3
       / 
      9  20
        /  
       15   7
    

    二叉树结构

    public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x){ val = x; }
    }
    

    解答

    前序遍历特点:节点按照 [根节点|左子树|右子树] 排序

    中序遍历特点:节点按照 [左子树|根节点|右子树] 排序

    根据以上特点,可得重构二叉树的步骤:

    1. 前序遍历的第一个元素,是整个二叉树的根节点(root)的值。
    2. 在中序遍历中查询根节点(root)的索引,由此索引,可以划分中序遍历(左子树的右边界、右子树的左边界)
    3. 根据子树的左右边界可以确定子树的节点数量,进而划分前序遍历,可以确定左右子节点的值
    class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            HashMap<Integer,Integer> dic = new HashMap<>();//存放中序遍历 <值,索引> 键值对,便于查询根节点值的索引
            for(int i = 0; i < inorder.length; i++) 
                dic.put(inorder[i],i);
            return build(preorder,0,0,inorder.length-1,dic);
        }
        public TreeNode build(int[] preorder,int pre_root,int in_left,int in_right,HashMap<Integer,Integer> dic){
            if(in_left>in_right) return null;
            TreeNode root = new TreeNode(preorder[pre_root]);
            int i = dic.get(root.val);//获取根节点在 中序遍历 中的索引
            root.left = build(preorder,pre_root+1,in_left,i-1,dic);//获取左子节点
            root.right = build(preorder,pre_root+i-in_left+1,i+1,in_right,dic);//获取又子节点
            return root;
        }
    }
    

    执行用时:2ms

    内存消耗:40.1MB

  • 相关阅读:
    [ Linux ] rsync 对异地服务器进行简单同步
    [ Skill ] 遍历整个项目设计的两个思路
    [ Skill ] 不常用的函数笔记
    [ Perl ] Getopt 使用模板
    [ Skill ] 两个 listBox 数据交换的模板
    [ Linux ] "真"后台 nohup
    [ VM ] VirtualBox 压缩 .vdi
    [ Skill ] Layout 工艺移植,还原库调用关系
    win8 hyper-v 禁用不必卸载虚拟机
    BM算法解析(计算机算法-设计与分析导论(第三版))
  • 原文地址:https://www.cnblogs.com/HenuAJY/p/13164317.html
Copyright © 2011-2022 走看看