请使用java来构造和遍历二叉树?

【分析】

二叉树的结构:根节点、左子树、右子树。其中左子树的值必须小于根节点,右子树的值必须大于根节点。构造这种树结构,就是创建一个类,并提供一个方法,当给定一个值时,它能够自动创建节点并自动挂到二叉树的合适位置。

二叉树的遍历:分为先序遍历、中序遍历和后序遍历。先序遍历:根、左、右。

中需遍历:左、根、右。

后续遍历:左、右、根。

二叉树的应用:加密解密、文件压缩、快速查询、快速遍历等。

1、构造二叉树的节点对象,并提供插入方法。

 1     private int data; //存放节点数据
 2     private BinaryTree left; //左子树
 3     private BinaryTree right; //右子树
 4     
 5     /**
 6      * 构造方法,创建新节点 
 7      */
 8     public BinaryTree(int data) {
 9         this.data = data;
10         this.left = null;
11         this.right = null;
12     }
13     
14     /**
15      * 插入新节点
16      */
17     public void insert(BinaryTree root, int data){
18         if(root !=null){
19             if(data <root.data){
20                 if(root.left ==null){     //左子树空位,插入
21                     root.left = new BinaryTree(data);
22                 }else{                    //左子树非空,将左子树作为根节点递归
23                     insert(root.left, data);
24                 }
25             }else{
26                 if(root.right ==null){
27                     root.right = new BinaryTree(data);
28                 }else{
29                     insert(root.right, data);
30                 }
31             }
32         }
33     }
34     

2.插入节点构造出二叉树,并通过先序遍历、中序遍历、后序遍历对二叉树进行遍历

 1 public static void main(String[] args) {
 2         BinaryTree root = new BinaryTree(6);  //创建根节点
 3         int[] a = {2,1,4,5,3,8,6,7,9};
 4         for (int i = 0; i < a.length; i++) {  //插入节点
 5             root.insert(root, a[i]);
 6         }
 7         
 8         preTraversal( root);
 9         midTraversal( root);
10         sufTraversal( root);
11     }
 1 //先序遍历
 2     public static void preTraversal(BinaryTree root){
 3         if (root !=null) {
 4             System.out.print(root.getData() +"-");
 5             preTraversal(root.getLeft());
 6             preTraversal(root.getRight());
 7         }
 8         
 9     }
10     
11     //中序遍历
12         public static void midTraversal(BinaryTree root){
13             if(root !=null){
14                 midTraversal(root.getLeft());
15                 System.out.print(root.getData()+"-");
16                 midTraversal(root.getRight());
17             }
18         }
19         
20     //后序遍历
21         public static void sufTraversal(BinaryTree root){
22             if(root !=null){
23             sufTraversal(root.getLeft());
24             sufTraversal(root.getRight());
25             System.out.print(root.getData()+"-");
26             }
27         }