根据前序和中序序列,建立二叉树(java实现)

本文介绍如何利用Java根据给定的前序和中序序列构建二叉树,并讨论了二叉树的后序遍历问题。通过这种方法,可以恢复二叉树的结构,前序遍历为{1,2,4,7,3,5,6,8},中序遍历为{4,7,2,1,5,3,8,6}。" 132340365,10794535,CAPL与SOME/IP:从函数到协议实现的深度解析,"['网络协议', 'CAPL', 'SOME/IP', '汽车通信', '网络']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据前序序列:int[] preSort={1,2,4,7,3,5,6,8};

中序序列:int[] inSort=new int[]{4,7,2,1,5,3,8,6};

建立二叉树,求后序遍历等问题。

前序遍历,中序遍历,后序遍历,层次遍历,四种遍历中,必须包含中序遍历+三选一,两个序列就可以恢复出二叉树的形态。


//方案一:
package com.mytest.mymain;


import java.util.Arrays;


 //定义节点
class BinaryTree{
public int value;
public BinaryTree leftNode;
public BinaryTree rightNode;
BinaryTree(int x) { value = x; }
}


public class ConstrontTree {

public static void main(String[] args) throws Exception {
int[] preSort={1,2,4,7,3,5,6,8};
int[] inSort=new int[]{4,7,2,1,5,3,8,6};
BinaryTree root=startBuildTree(preSort,inSort);
}
//01递归生成树
private static BinaryTree startBuildTree(int[] preSort,int[] inSort) throws Exception {
//异常判断
if(preSort==null || inSort==null){
return null;
}
if(preSort.length!=inSort.length){
throw new Exception("不满足条件的非法输入!");
}

BinaryTree root=null;
for(int i=0;i<inSort.length;i++){
if(inSort[i]==preSort[0]){
root=new BinaryTree(preSort[0]);
System.out.println(preSort[0]);

root.leftNode=startBuildTree(
Arrays.copyOfRange(preSort, 1, i+1),
Arrays.copyOfRange(inSort, 0, i));
root.rightNode=startBuildTree(
Arrays.copyOfRange(preSort, i+1, preSort.length),
Arrays.copyOfRange(inSort, i+1, inSort.length));
}
}


return root;
}


}
//方案二:
//对于查找中序序列中根节点所在位置做进一步优化:红色部分对比
publicclass Solution {
   
    publicTreeNode reConstructBinaryTree(int[] pre,int[] in) {
               if(pre==null||in==null){
            returnnull;
        }
 
        java.util.HashMap<Integer,Integer> map= newjava.util.HashMap<Integer, Integer>();
        for(inti=0;i<in.length;i++){
            map.put(in[i],i);
        }

        returnpreIn(pre,0,pre.length-1,in,0,in.length-1,map);
    }
     
      publicTreeNode preIn(int[] p,intpi,intpj,int[] 


n,intni,intnj,java.util.HashMap<Integer,Integer> map){
 
        if(pi>pj){
            returnnull;
        }
        TreeNode head=newTreeNode(p[pi]);
        intindex=map.get(p[pi]);                  //这样比原始方案一的方式效率要高,值得思考的地方
        head.left=preIn(p,pi+1,pi+index-ni,n,ni,index-1,map);
        head.right=preIn(p,pi+index-ni+1,pj,n,index+1,nj,map);
        returnhead;
    }










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值