一,定义一个节点类:
package test; public class Node { private int data; private Node left; private Node right; public Node(int data) { this.data = data; } public int getData() { return data; } public void setData(int data) { this.data = data; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } }
二,定义一个算法实现类:
package test; public class FindTree { private void visit(int data) { System.out.print(data+"--"); } public void preOrder(Node root) { if(root == null) { return; } visit(root.getData()); preOrder(root.getLeft()); preOrder(root.getRight()); } public void inOrder(Node root) { if(root == null) { return; } inOrder(root.getLeft()); visit(root.getData()); inOrder(root.getRight()); } public void afterOrder(Node root) { if(root == null) { return; } afterOrder(root.getLeft()); afterOrder(root.getRight()); visit(root.getData()); } }
三,构建一个二叉树
package test; public class TestTree { public static void main(String[] args) { FindTree ft = new FindTree(); int[] array = {12,76,35,22,16,48,90,46,9,40}; int j = 0; Node root = new Node(array[j]); for(int i = 1; i< array.length; i++) { insert(root, array[i]); } System.out.println("preorder----------------------------------"); ft.preOrder(root); System.out.println(" inorder----------------------------------"); ft.inOrder(root); System.out.println(" afterorder----------------------------------"); ft.afterOrder(root); } private static void insert(Node root, int data) { //二叉树中左边的孩子节点小于父节点,右边的孩子节点大于父节点 if(root.getData() < data) { if(root.getRight() == null) { root.setRight(new Node(data)); } else { insert(root.getRight(), data); } } else { if(root.getLeft() == null) { root.setLeft(new Node(data)); } else { insert(root.getLeft(), data); } } } }
四,打印结果:
preorder----------------------------------
12--9--76--35--22--16--48--46--40--90--
inorder----------------------------------
9--12--16--22--35--40--46--48--76--90--
afterorder----------------------------------
9--16--22--40--46--48--35--90--76--12--