首页 > 代码库 > 数据结构之树(Java 实现版)

数据结构之树(Java 实现版)

实现功能:

  1.实现了树的构建;

  2.实现了树的前序递归遍历、后序递归遍历、中序递归遍历;

 1 class BinaryTreeNode{
 2         int data;
 3         BinaryTreeNode leftNode = null, rightNode = null;
 4         
 5         public void setBinaryTreeNode(int data) {
 6             this.data =http://www.mamicode.com/ data;
 7         }
 8         public void setLeftNode(BinaryTreeNode leftNode) {
 9             this.leftNode = leftNode;
10         }
11         public void setRightNode(BinaryTreeNode rightNode) {
12             this.rightNode = rightNode;
13         }
14     }
15 
16 class BinaryTree{
17     BinaryTreeNode[] btn;
18     BinaryTreeNode rooNode;
19     int NodeSize;
20     
21     public BinaryTree(int[] arrayNode) {
22         NodeSize = arrayNode.length;
23         btn = new BinaryTreeNode[NodeSize];
24         
25         //把arrayNode元素转化为节点
26         for(int i = 0; i < NodeSize; i++){
27             btn[i] = new BinaryTreeNode();
28             btn[i].setBinaryTreeNode(arrayNode[i]);
29             if(i == 0){
30                 rooNode = btn[i];
31             }
32         }
33         //把二叉树的左右子树节点补全
34         for(int j = 0; j <= (NodeSize - 2)/2; j++){
35             btn[j].setLeftNode(btn[2*j + 1]);
36             btn[j].setRightNode(btn[2*j + 2]);
37         }
38     }
39     //递归方法前序遍历
40     void preOrder(BinaryTreeNode btn){
41         BinaryTreeNode root = btn;
42         if(root != null){
43             printNode(root);
44             inOrder(root.leftNode);
45             inOrder(root.rightNode);
46         }
47     }
48     //递归方法中序遍历
49     void inOrder(BinaryTreeNode btn){
50         BinaryTreeNode root = btn;
51         
52         if(root != null){
53             inOrder(root.leftNode);
54             printNode(root);
55             inOrder(root.rightNode);
56         }
57     }
58     //递归方法后序遍历
59     void postOrder(BinaryTreeNode btn){
60         BinaryTreeNode root = btn;
61         
62         if(root != null){
63             postOrder(root.leftNode);
64             postOrder(root.rightNode);
65             printNode(root);
66         }
67     }
68     //打印节点信息
69     static void printNode(BinaryTreeNode btn){
70         int a = btn.data;
71         System.out.println(a);
72     }
73 }
74 
75 public class Tree {
76     public static void main(String[] args) {
77         int[] arrayNode = new int[]{1,2,3,4,5,6,7,8,9};
78         BinaryTree bt = new BinaryTree(arrayNode);
79         System.out.println("inOrder:");
80         bt.inOrder(bt.rooNode);
81         System.out.println("preOrder:");
82         bt.preOrder(bt.rooNode);
83         System.out.println("postOrder:");
84         bt.postOrder(bt.rooNode);
85     }
86 }

 

数据结构之树(Java 实现版)