package com.wujie.tree;
public class Tree {
public static void main(String[] args) {
TreeNode root = new TreeNode("Root");
TreeNode a = new TreeNode("A");
TreeNode b = new TreeNode("B");
TreeNode c = new TreeNode("C");
TreeNode d = new TreeNode("D");
TreeNode e = new TreeNode("E");
TreeNode f = new TreeNode("F");
TreeNode g = new TreeNode("G");
TreeNode h = new TreeNode("H");
root.left = a;
root.right = b;
a.left = e;
a.right = f;
b.left = g;
g.right = h;
root.firstList(root);
System.out.println();
root.midList(root);
System.out.println();
root.endList(root);
}
}
class TreeNode {
public String element;
public TreeNode left;
public TreeNode right;
public TreeNode(String element) {
this.element = element;
}
/**
* 先序遍历
*/
public void firstList(TreeNode root) {
System.out.print(root.element + "->");
if (root.left != null) {
this.firstList(root.left);
}
if (root.right != null) {
this.firstList(root.right);
}
}
/**
* 中序遍历
*/
public void midList(TreeNode root) {
if (root.left != null) {
this.midList(root.left);
}
System.out.print(root.element + "->");
if (root.right != null) {
this.midList(root.right);
}
}
/**
* 后序遍历
*/
public void endList(TreeNode root) {
if (root.left != null) {
this.endList(root.left);
}
if (root.right != null) {
this.endList(root.right);
}
System.out.print(root.element + "->");
}
}