已知二叉树前序和中序,算法写出后续遍历的结果

 1 package com.S;
 2 
 3 import java.util.Arrays;
 4 
 5 public class Tree {
 6 
 7     int data;
 8     Tree left;
 9     Tree right;
10 
11     public Tree(int data){
12         this.data = data;
13     }
14     public Tree(int data, Tree left, Tree right){
15         this.data = data;
16         this.left = left;
17         this.right = right;
18     }
19 
20     public void afterShow(){
21         //
22         if(left != null){
23             left.afterShow();
24         }
25         //
26         if(right != null){
27             right.afterShow();
28         }
29         //自己
30         System.out.println(data);
31     }
32 
33     /**
34      * 重建树
35      * @param preOrders  树的前序
36      * @param inOrders   树的中序
37      * @return
38      */
39     public Tree buildTree(int[] preOrders, int[] inOrders){
40         //递归截止条件,有一个为空,就说明没有子节点了
41         if(preOrders.length == 0 || inOrders.length == 0){
42             return null;
43         }
44         //每轮的根节点就是preOrders的第一个
45         Tree root = new Tree(preOrders[0]);
46         //根据inOrders查找到根节点的下标,返回index
47         int index = search(inOrders, root.data);
48         if(index >= 0){
49             //Arrays.copyOfRange(preOrders, 1, index+1),截取preOrders,从1到index+1,前包后不包
50             root.left = buildTree(Arrays.copyOfRange(preOrders, 1, index+1), Arrays.copyOfRange(inOrders, 0, index));
51             root.right = buildTree(Arrays.copyOfRange(preOrders, index+1, preOrders.length), Arrays.copyOfRange(inOrders, index+1, inOrders.length));
52         }
53         return root;
54     }
55 
56     /**
57      * 根据inOrders查找根节点的下标,目的是找到左子树和右子树的分界
58      * @param inOrders  中序
59      * @param data   根节点
60      * @return
61      */
62     public int search(int[] inOrders, int data){
63         for (int i = 0; i < inOrders.length; i++) {
64             if(data == inOrders[i]){
65                 return i;
66             }
67         }
68         return -1;
69     }
70 
71 
72     public static void main(String[] args) {
73        int[] preOrders = {1,2,4,5,3,6,7};
74        int[] inOrders = {4,2,5,1,6,3,7};
75        new Tree(preOrders[0]).buildTree(preOrders, inOrders).afterShow();
76     }
77 
78 }

 

posted @ 2020-03-26 14:35  motorye  阅读(259)  评论(0编辑  收藏  举报