根据前序遍历和中序遍历重建二叉树
实例:
8
1 2 4 7 3 5 6 8
4 7 2 1 5 3 8 6
import java.util.Scanner; /** * 重建二叉树 * 8 1 2 4 7 3 5 6 8 4 7 2 1 5 3 8 6 * @author DELL * */ public class ReconstructionTree { private static class Node{ private Node left=null; private Node right=null; private int value; public Node(int value) { // TODO Auto-generated constructor stub this.value=value; } } public static void main(String[] args) { ReconstructionTree resTree=new ReconstructionTree(); Scanner scanner=new Scanner(System.in); System.out.println("请输入:"); int[] preOrder; int[] inOrder; int length; while(scanner.hasNext()){ length=scanner.nextInt(); preOrder=new int[length]; inOrder=new int[length]; for (int i = 0; i < preOrder.length; i++) { preOrder[i]=scanner.nextInt(); } for(int i=0;i<inOrder.length;i++){ inOrder[i]=scanner.nextInt(); } //重建二叉树,根据前序遍历和中序遍历 Node head=resTree.reconstruction(preOrder, inOrder, 0, 0, length-1); System.out.println("先序遍历"); printPreTree(head); System.out.println("\n中序遍历"); printInOrderTree(head); System.out.println("\n后续遍历"); printAfterTree(head); } } private static void printAfterTree(Node head){ if(head!=null){ printAfterTree(head.left); printAfterTree(head.right); System.out.print(head.value+" "); } } private static void printInOrderTree(Node head){ if(head!=null){ printInOrderTree(head.left); System.out.print(head.value+" "); printInOrderTree(head.right); } } private static void printPreTree(Node head) { // TODO Auto-generated method stub if(head!=null){ System.out.print(head.value+" "); printPreTree(head.left); printPreTree(head.right); }else{ return; } } private static int findIndex(int[] preOrder, int[] inOrder,int value, int beg, int end) { // TODO Auto-generated method stub for(int i=beg;i<=end;i++){ if(inOrder[i]==value){ return i; } } System.out.println("not found!"); return -1; } private Node reconstruction(int[] preOrder,int[] inOrder,int i,int beg,int end){ System.out.println("beg="+beg+"; end="+end); if(beg>end){ return null; } Node node=new Node(preOrder[i]); int index=findIndex(preOrder, inOrder, preOrder[i], beg, end); if(index==beg){ node.left=null; node.right=reconstruction(preOrder,inOrder,i+1,index+1,end); }else if(index==end){ node.left=reconstruction(preOrder, inOrder, i+1, beg, index-1); node.right=null; }else{ node.left=reconstruction(preOrder, inOrder, i+1, beg, index-1); node.right=reconstruction(preOrder,inOrder,i+index-beg+1,index+1,end); } return node; } }