1.二叉树类:
package com.j2se.test; public class BinaryTree { int data; //根节点数据 BinaryTree left; BinaryTree right; /** * 二叉树构造方法 * @param data */ public BinaryTree(int data) { this.data = data; left = null; right = null; } public void insert(BinaryTree root,int data) { if(data>root.data) { if(root.right==null) { root.right = new BinaryTree(data); } else { this.insert(root.right, data); } } else { if(root.left==null) { root.left = new BinaryTree(data); }else { this.insert(root.left, data); } } } }
2.测试类:
package com.j2se.test; public class BinaryTreePreorder { public static void preOrder(BinaryTree root) { if(root!=null){ System.out.print(root.data+"-"); preOrder(root.left); preOrder(root.right); } } public static void inOrder(BinaryTree root){ if(root!=null) { inOrder(root.left); System.out.print(root.data+"--"); inOrder(root.right); } } public static void postOrder(BinaryTree root) { if(root!=null) { postOrder(root.left); postOrder(root.right); System.out.print(root.data+"--"); } } public static void main(String[] args) { int[] array = {12,76,35,22,16,48,90,46,9,40}; BinaryTree root = new BinaryTree(array[0]);//创建二叉树 for(int i=1;i<array.length;i++) { root.insert(root, array[i]);//向二叉树中插入数据 } System.out.println("先根遍历:"); preOrder(root); System.out.println(); System.out.println("中根遍历:"); inOrder(root); System.out.println(); System.out.println("后根遍历:"); postOrder(root); } }
3.创建好的二叉树图形:
4.测试类打印结果:
先根遍历:
12-9-76-35-22-16-48-46-40-90-
中根遍历:
9--12--16--22--35--40--46--48--76--90--
后根遍历:
9--16--22--40--46--48--35--90--76--12--