public class Test_01 {
static class Node {
Node parent;
Node left;
Node right;
String content;
boolean visited;
Node(String content) {
this.content = content;
}
void setLeft(Node left) {
this.left = left;
left.parent = this;
}
void setRight(Node right) {
this.right = right;
right.parent = this;
}
}
public static void main(String[] args) {
Node na = new Node("A");
Node nb = new Node("B");
Node nc = new Node("C");
Node nd = new Node("D");
Node ne = new Node("E");
Node nf = new Node("F");
Node ng = new Node("G");
Node nh = new Node("H");
Node ni = new Node("I");
na.setLeft(nb);
na.setRight(nc);
nb.setLeft(nd);
nb.setRight(ne);
nc.setLeft(nf);
nc.setRight(ng);
ne.setLeft(ni);
nf.setLeft(nh);
test1(na);
System.out.println();
System.out.println("==========================");
test2(na);
System.out.println();
System.out.println("==========================");
test3(na);
System.out.println();
System.out.println("==========================");
test4(na);
System.out.println();
System.out.println("==========================");
test5(na);
System.out.println();
System.out.println("==========================");
test6(na);
}
private static void test1(Node root) {
if (root != null) {
System.out.print(root.content+",");
test1(root.left);
test1(root.right);
}
}
private static void test2(Node root) {
if (root != null) {
test2(root.left);
System.out.print(root.content+",");
test2(root.right);
}
}
private static void test3(Node root) {
if (root != null) {
test3(root.left);
test3(root.right);
System.out.print(root.content+",");
}
}
private static void test4(Node root) {
Stack<Node> stack = new Stack<Node>();
Node current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.peek();
stack.pop();
System.out.print(current.content+",");
current = current.right;
}
}
private static void test5(Node root) {
Stack<Node> stack = new Stack<Node>();
Node current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
System.out.print(current.content+",");
stack.push(current);
current = current.left;
}
current = stack.peek();
stack.pop();
current = current.right;
}
}
private static void test6(Node root) {
Stack<Node> stack = new Stack<Node>();
Node current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.peek();
stack.pop();
if (!current.visited) {
current.visited = true;
stack.push(current);
current = current.right;
} else {
System.out.print(current.content+",");
current = null;
}
}
}
}
时间: 2024-10-15 01:18:13