import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.LinkedList;
/**
* @author Joeson Chan
*/
public class Traverse {
@Data
@NoArgsConstructor
public static class Node {
public Node(String data, Node lc, Node rc) {
this.data = data;
this.lc = lc;
this.rc = rc;
}
private String data;
private Node lc;
private Node rc;
}
/**
* 前序遍历递归
*/
public static void preDiv(Node node){
if(null == node){
return;
}
System.out.print(node.data + " ");
preDiv(node.lc);
preDiv(node.rc);
}
/**
* 中序遍历递归
* @param node
*/
public static void midDiv(Node node){
if(null == node){
return;
}
midDiv(node.lc);
System.out.print(node.data + " ");
midDiv(node.rc);
}
/**
* 后序遍历递归
*/
public static void postDiv(Node node){
if(null == node){
return;
}
midDiv(node.lc);
midDiv(node.rc);
System.out.print(node.data + " ");
}
/**
* 先序遍历
*/
public static void pre(Node root) {
if (null == root) {
return;
}
LinkedList<Node> stack = new LinkedList<>();
Node node = root;
while (node != null || !stack.isEmpty()) {
if (node != null) {
System.out.print(node.data + " ");
stack.push(node);
node = node.lc;
} else { //pNode == null && !stack.isEmpty()
node = stack.pop();
node = node.rc;
}
}
}
/**
* 中序遍历
*/
public static void mid(Node root) {
if (null == root) {
return;
}
LinkedList<Node> stack = new LinkedList<>();
Node node = root;
while (null != node || !stack.isEmpty()) {
if (node != null) {
stack.push(node);
node = node.lc;
} else { //pNode == null && !stack.isEmpty()
node = stack.pop();
System.out.print(node.data + " ");
node = node.rc;
}
}
}
/**
* 后续遍历
*/
public static void post(Node root) {
if (null == root) {
return;
}
LinkedList<Node> stack = new LinkedList<>();
LinkedList<Node> output = new LinkedList<>();
Node node = root;
while (node != null || stack.size() > 0) {
if (node != null) {
output.push(node);
stack.push(node);
node = node.rc;
} else {
node = stack.pop();
node = node.lc;
}
}
while (output.size() > 0) {
System.out.print(output.pop().data + " ");
}
}
private static Node mock() {
Node F = new Node("F", null, null);
Node E = new Node("E", null, null);
Node B = new Node("B", F, E);
Node G = new Node("G", null, null);
Node H = new Node("H", null, null);
Node C = new Node("C", G, H);
Node A = new Node("A", B, C);
return A;
}
private static void testPre() {
preDiv(mock());
System.out.println();
}
private static void testMid() {
midDiv(mock());
System.out.println();
}
private static void testPost() {
post(mock());
System.out.println();
}
public static void main(String[] args) {
testPre();
testMid();
testPost();
}
}