记录二叉树的遍历
public class PrintTree {
public static class Node {
Node left;
Node right;
Integer value;
Node(int value) {
this.value = value;
}
}
public static void main(String[] args) {
Node node = new Node(7);
node.left = new Node(3);
node.right = new Node(6);
node.left.left = new Node(1);
node.left.right = new Node(2);
node.right.left = new Node(4);
node.right.right = new Node(5);
// postorderForeach(node); // 123
// inorderForeach(node); // 213
// preorderForeach(node); // 7312
}
// 非递归, 实现遍历 <前序, ^中序, >后续
private static void postorderForeach(Node root) {
Stack<Node> stack = new Stack<>();
stack.push(root);
Node lastNode = null;
Node cur;
while (!stack.isEmpty()) {
cur = stack.peek();
if (cur.left != null && cur.left != lastNode && cur.right != lastNode) {
stack.push(cur.left);
continue;
}
if (cur.right != null && cur.right != lastNode) {
stack.push(cur.right);
continue;
}
System.out.println(cur.value);
lastNode = stack.pop();
}
}
// 中序遍历
private static void inorderForeach(Node root) {
Stack<Node> stack = new Stack<>();
Node cur = root;
while (cur != null || !stack.isEmpty()) {
if (cur != null) {
stack.push(cur);
// cur = cur.left;
cur = cur.right;
continue;
}
cur = stack.pop();
System.out.println(cur.value);
// cur = cur.right;
cur = cur.left;
}
}
// 前序遍历
private static void preorderForeach(Node root) {
Stack<Node> stack = new Stack<>();
Node cur = root;
while (cur != null || !stack.isEmpty()) {
if (cur != null) {
System.out.println(cur.value);
stack.push(cur);
cur = cur.left;
continue;
}
cur = stack.pop();
cur = cur.right;
}
}
}