节点代码
public class Node { private Node left; private Node right; private int value; public Node(int value) { this.value = value; } @Override public String toString() { return "Node{" + "value=" + value + '}'; } public int getValue() { return value; } 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; } }
树代码
public class BinaryTree { private Node root; public BinaryTree(Node root) { this.root = root; } public void preOrder(){ preOrder(root); } public void midOrder(){ midOrder(root); } public void postOrder(){ postOrder(root); } /** * 前序遍历 */ private void preOrder(Node node){ if (node==null) { return; } System.out.println(node.getValue()); preOrder(node.getLeft()); preOrder(node.getRight()); } /** * 中序遍历 */ private void midOrder(Node node){ if (node==null) { return; } midOrder(node.getLeft()); System.out.println(node.getValue()); midOrder(node.getRight()); } /** * 后序遍历 */ private void postOrder(Node node){ if (node==null) { return; } postOrder(node.getLeft()); postOrder(node.getRight()); System.out.println(node.getValue()); } }
测试代码
public class Test { public static void main(String[] args) { testBinaryTree(); } private static void testBinaryTree() { Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); Node node4 = new Node(4); Node node5 = new Node(5); Node node6 = new Node(6); Node node7 = new Node(7); node1.setLeft(node2); node1.setRight(node3); node2.setLeft(node4); node2.setRight(node5); node3.setLeft(node6); node3.setRight(node7); BinaryTree binaryTree = new BinaryTree(node1); binaryTree.preOrder();//前序遍历 1245367 binaryTree.midOrder();//中序遍历 4251637 binaryTree.postOrder();//后序遍历 4526731 } }