Java:根据二叉树的前序,中序遍历构造二叉树

递归

直接上代码:

 1 package BinaryTree;
 2 
 3 import java.util.Arrays;
 4 
 5 class BintryT{
 6     Object data;
 7     BintryT lChild;
 8     BintryT rChild;
 9     BintryT(Object obj){
10         this.data = obj;
11     }
12 }
13 
14 public class CreateBT {
15     public static void main(String[] args) throws Exception{
16         int [] pre = {34,59,56,445,8745,2,33,76};
17         int [] in = {445,56,59,8745,34,33,2,76};
18         //int [] pre = {1,2,4,7,3,5,6,8};
19         //int [] in = {4,7,2,1,5,3,8,6};
20         
21         @SuppressWarnings("unused")
22         BintryT root = createTWith_pre_in(pre,in);
23     }
24     public static BintryT createTWith_pre_in(int[] pre,int[] in) throws Exception{
25         if(pre.length==0||in.length==0){
26             return null;
27         }
28         BintryT root = new BintryT(pre[0]);
29         for(int i=0;i<in.length;i++){
30             if(pre[0]==in[i]){
31                 System.out.println(pre[0]);
32                 root.lChild = (createTWith_pre_in(Arrays.copyOfRange(pre, 1, i+1),Arrays.copyOfRange(in, 0, i)));
33                 root.rChild = (createTWith_pre_in(Arrays.copyOfRange(pre, i+1, pre.length),Arrays.copyOfRange(in, i+1, in.length)));
34             }
35         }
36         return root;
37     }
38 }

 

转载于:https://www.cnblogs.com/fanghuiplus/p/9522517.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值