|
|
@ -33,18 +33,18 @@ public class Code02_UnRecursiveTraversalBT {
|
|
|
|
System.out.println();
|
|
|
|
System.out.println();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public static void in(Node head) {
|
|
|
|
public static void in(Node cur) {
|
|
|
|
System.out.print("in-order: ");
|
|
|
|
System.out.print("in-order: ");
|
|
|
|
if (head != null) {
|
|
|
|
if (cur != null) {
|
|
|
|
Stack<Node> stack = new Stack<Node>();
|
|
|
|
Stack<Node> stack = new Stack<Node>();
|
|
|
|
while (!stack.isEmpty() || head != null) {
|
|
|
|
while (!stack.isEmpty() || cur != null) {
|
|
|
|
if (head != null) {
|
|
|
|
if (cur != null) {
|
|
|
|
stack.push(head);
|
|
|
|
stack.push(cur);
|
|
|
|
head = head.left;
|
|
|
|
cur = cur.left;
|
|
|
|
} else {
|
|
|
|
} else {
|
|
|
|
head = stack.pop();
|
|
|
|
cur = stack.pop();
|
|
|
|
System.out.print(head.value + " ");
|
|
|
|
System.out.print(cur.value + " ");
|
|
|
|
head = head.right;
|
|
|
|
cur = cur.right;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
@ -58,7 +58,7 @@ public class Code02_UnRecursiveTraversalBT {
|
|
|
|
Stack<Node> s2 = new Stack<Node>();
|
|
|
|
Stack<Node> s2 = new Stack<Node>();
|
|
|
|
s1.push(head);
|
|
|
|
s1.push(head);
|
|
|
|
while (!s1.isEmpty()) {
|
|
|
|
while (!s1.isEmpty()) {
|
|
|
|
head = s1.pop();
|
|
|
|
head = s1.pop(); // 头 右 左
|
|
|
|
s2.push(head);
|
|
|
|
s2.push(head);
|
|
|
|
if (head.left != null) {
|
|
|
|
if (head.left != null) {
|
|
|
|
s1.push(head.left);
|
|
|
|
s1.push(head.left);
|
|
|
@ -67,6 +67,7 @@ public class Code02_UnRecursiveTraversalBT {
|
|
|
|
s1.push(head.right);
|
|
|
|
s1.push(head.right);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 左 右 头
|
|
|
|
while (!s2.isEmpty()) {
|
|
|
|
while (!s2.isEmpty()) {
|
|
|
|
System.out.print(s2.pop().value + " ");
|
|
|
|
System.out.print(s2.pop().value + " ");
|
|
|
|
}
|
|
|
|
}
|
|
|
|