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 }
作者:shareidea
出处:https://www.cnblogs.com/shareidea94/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。