Day18|106.从中序与后序遍历序列构造二叉树

一、106.从中序与后序遍历序列构造二叉树

题目链接:https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
文章链接:https://programmercarl.com/0106.%E4%BB%8E%E4%B8%AD%E5%BA%8F%E4%B8%8E%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
视频链接:https://www.bilibili.com/video/BV1vW4y1i7dn/?vd_source=721f65ae0501389782be0dcb48a2c421

package com.eighteenday.tree;

import java.util.Map;

/**
 * 题目:根据一颗树的中序遍历与后序遍历构造二叉树
 * 注意:你可以假设树中没有重复的元素
 */
public class BuildTree {

    Map<Integer,Integer> map;   //用map保存中序序列的数值对应位置
    public TreeNode buildTree(int[] inorder,int[] postorder){
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i],i);    //key:数组中的值,value:i
        }

        return findNode(inorder,0,inorder.length,postorder,0,postorder.length);
    }

    public TreeNode findNode(int[] inorder,int inBegin,int inEnd,int[] postorder,int postBegin,int postEnd){
        //参数里的范围都是左闭右开
        //大白话就是:判断传进的数组是否为空
        if (inBegin >= inEnd || postBegin >= postEnd){  //不满足左闭右开,说明没有元素,返回空树
            return null;
        }
        int rootIndex = map.get(postorder[postEnd-1]); //找到后序遍历的最后一个元素在中序遍历中的位置
        TreeNode root = new TreeNode(inorder[rootIndex]);//构造节点
        int lenOfLeft = rootIndex - inBegin ;  //保存中序左子树个数,用来确定后序数列的个数,tip:算的是大小(长度)
        //
        root.left = findNode(inorder,inBegin,rootIndex,postorder,postBegin,postBegin+lenOfLeft);

        root.right = findNode(inorder,rootIndex+1,inEnd,postorder,postBegin+lenOfLeft,postEnd);

        return root;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值