04 重建二叉树


输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 import java.util.*;
11 public class Solution {
12     static public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
13         if(pre== null || in ==null)
14             return null;
15         if ( pre.length != in.length){
16             System.out.println("前序遍历长度与中序遍历长度不同,输入错误");
17         }
18         TreeNode root = reConstructBinaryTree(pre,0,pre.length -1,in, 0,in.length -1);
19         return root;
20     }
21     public static TreeNode reConstructBinaryTree(int [] pre,int startpre, int endpre,int [] in,int startin,int endin){
22         if ( startpre > endpre || startin > endin)
23             return null;
24         TreeNode root = new TreeNode( pre[startpre]);
25         for (int i = startin; i <= endin; i++){
26             if(pre[startpre] == in[i]){
27                 root.left = reConstructBinaryTree(pre,startpre+1,startpre+i-startin,in, startin,i-1);
28                 root.right = reConstructBinaryTree(pre,startpre+i-startin +1,endpre,in, i+1,endin);
29             }
30         }
31         return root;
32     }
33     public static void main(String [] args){
34         Scanner sc = new Scanner(System.in);
35         System.out.println("请输入前序遍历序列的长度");
36         int lengthpre = sc.nextInt();
37         int [] pre = new int[lengthpre];
38         System.out.println("请输入前序遍历序列");
39         for (int i =0;i< lengthpre;i++){
40             pre[i] = sc.nextInt();
41         }
42         System.out.println("请输入中序遍历序列的长度");
43         int lengthin = sc.nextInt();
44         int [] in = new int[lengthin];
45         System.out.println("请输入中序遍历序列");
46         for(int j = 0; j< lengthin;j++){
47             pre[j] = sc.nextInt();
48         }
49         reConstructBinaryTree(pre,in);
50     }
51 }

 

转载于:https://www.cnblogs.com/shareidea94/p/11095559.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值