树
二.代码,两个class
- public class Node {
- /** 名称 */
- private String name;
- /** 左节点 */
- private Node left;
- /** 右节点 */
- private Node right;
- //get.set略
- public Node(String n, Node l, Node r) {
- name = n;
- left = l;
- right = r;
- }
- }
- public class Admin {
- public static void main(String[] args) {
- test();
- }
- private static void test() {
- // 先序
- xian(init());
- System.out.println();
- // 中序
- zhong(init());
- System.out.println();
- // 后序
- hou(init());
- }
- /** 初始化 */
- private static Node init() {
- Node nodeG = new Node("G", null, null);
- Node nodeF = new Node("F", null, null);
- Node nodeE = new Node("E", null, null);
- Node nodeD = new Node("D", null, nodeG);
- Node nodeC = new Node("C", nodeF, null);
- Node nodeB = new Node("B", nodeD, nodeE);
- Node nodeA = new Node("A", nodeB, nodeC);
- return nodeA;
- }
- private static void print(Node node) {
- System.out.print(node.getName() + "==>");
- }
- /** 先序 中->左->右 */
- public static void xian(Node node) {
- if (node != null) {
- print(node);
- xian(node.getLeft());
- xian(node.getRight());
- }
- }
- /** 中序 左->中->右 */
- public static void zhong(Node node) {
- if (node != null) {
- zhong(node.getLeft());
- print(node);
- zhong(node.getRight());
- }
- }
- /** 后序 左->右->中 */
- public static void hou(Node node) {
- if (node != null) {
- hou(node.getLeft());
- hou(node.getRight());
- print(node);
- }
- }
- }
转载地址:http://xiaojianhx.iteye.com/blog/491481