首先创建节点类,并在里面添加了一个创建树的方法,调用后就可以返回一个包含7个节点的二叉树。- public class Node {
- // 节点值
- public int value;
- // 左子节点
- public Node left;
- // 右子节点
- public Node right;
- Node(int va) {
- value = va;
- }
- Node(int va, Node le, Node ri) {
- value = va;
- left = le;
- ri = right;
- }
- /**
- * 创建一颗二叉树
- *
- * @return 根节点
- */
- public static Node createTree() {
- Node root = new Node(0);
- 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);
- root.left = node1;
- root.right = node2;
- node1.left = node3;
- node1.right = node4;
- node2.left = node5;
- node2.right = node6;
- node3.left = node7;
- return root;
- }
- }
创建遍历类,在该类里实现各种遍历方法。
点击(此处)折叠或打开
- public class Algorithm {
- public static void main(String[] args) {
- Node root=Node.createTree();
- System.out.print("前序遍历: ");
- new Traverse().proOrder(root);
- System.out.println();
- System.out.print("前序递归遍历: ");
- new Traverse().recursiveProOrder(root);
- System.out.println();
- System.out.print("中序遍历: ");
- new Traverse().inOrder(root);
- System.out.println();
- System.out.print("中序递归遍历: ");
- new Traverse().recursiveInOrder(root);
- System.out.println();
- System.out.print("后序遍历: ");
- new Traverse().postOrder(root);
- System.out.println();
- System.out.print("后序递归遍历: ");
- new Traverse().recursivePostOrder(root);
- }
前序遍历: 01374256
前序递归遍历: 01374256
中序遍历: 73140526
中序递归遍历: 73140526
后序遍历: 73415620
后序递归遍历: 73415620
阅读(207) | 评论(0) | 转发(0) |