package node;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class TraverseNode {
private static class TreeNode {
String value;
TreeNode left;
TreeNode right;
public TreeNode(String val) {
this.value = val;
}
}
public static void main(String[] args) {
TreeNode n0 = new TreeNode("G");
TreeNode n11 = new TreeNode("D");
TreeNode n12 = new TreeNode("M");
n0.left = n11;
n0.right = n12;
TreeNode n21 = new TreeNode("A");
TreeNode n22 = new TreeNode("F");
n11.left = n21;
n11.right = n22;
TreeNode n23 = new TreeNode("H");
TreeNode n24 = new TreeNode("Z");
n12.left = n23;
n12.right = n24;
TreeNode n31 = new TreeNode("E");
n22.left = n31;
//preOrderTraverse(n0);
//levelOrderTraverse(n0);
postOrderTraverse(n0);
}
//层次遍历: GDMAFHZE
public static void levelOrderTraverse(TreeNode node) {
if (node == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()) {
TreeNode poll = queue.poll();
System.out.print(poll.value + "\t");
if (poll.left != null) {
queue.add(poll.left);
}
if (poll.right != null) {
queue.add(poll.right);
}
}
}
//前序遍历: GDAFEMHZ
public static void preOrderTraverse(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode pop = stack.pop();
System.out.print(pop.value + "\t");
if (pop.right != null) {
stack.push(pop.right);
}
if (pop.left != null) {
stack.push(pop.left);
}
}
}
//中序遍历:ADEFGHMZ
public static void midOrderTraverse(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
TreeNode pop = stack.pop();
System.out.print(pop.value + "\t");
root = root.right;
}
}
}
//后序遍历,双栈:AEFDHZMG
public static void postOrderTraverse(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.push(root);
while (!stack1.isEmpty()) {
root = stack1.pop();
stack2.push(root);
if (root.left != null) {
stack1.push(root.left);
}
if (root.right != null) {
stack1.push(root.right);
}
}
while (!stack2.isEmpty()){
System.out.print(stack2.pop().value+"\t");
}
}
}