二叉树的两种遍历:
递归版:
public static void preOrder(Node head) {
if (head == null) return;
System.out.print(head.value + " ");
preOrder(head.left);
preOrder(head.right);
}
public static void inOrder(Node head) {
if (head == null) return;
inOrder(head.left);
System.out.print(head.value + " ");
inOrder(head.right);
}
public static void postOrder(Node head) {
if (head == null) return;
postOrder(head.left);
postOrder(head.right);
System.out.print(head.value + " ");
}
非递归版:
public static void preOrderUnRecur(Node head) {
if (head != null) {
Stack<Node> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()) {
head = stack.pop();
System.out.print(head.value + " ");
if (head.right != null) stack.push(head.right);
if (head.left != null) stack.push(head.left);
}
}
System.out.println();
}
public static void inOrderUnRecur(Node head) {
if (head != null) {
Stack<Node> stack = new Stack<>();
while (head != null || !stack.isEmpty()) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}
System.out.println();
}
public static void posOrderUnRecur(Node head) {
if (head != null) {
Stack<Node> stack1 = new Stack<>();
Stack<Node> stack2 = new Stack<>();
stack1.push(head);
while (!stack1.isEmpty()) {
head = stack1.pop();
stack2.push(head);
if (head.left != null) stack1.push(head.left);
if (head.right != null) stack1.push(head.right);
}
while (!stack2.isEmpty()) {
head = stack2.pop();
System.out.print(head.value + " ");
}
}
System.out.println();
}
测试代码:
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static void main(String[] args) {
Node head = new Node(5);
head.left = new Node(3);
head.right = new Node(8);
head.left.left = new Node(2);
head.left.right = new Node(4);
head.left.left.left = new Node(1);
head.right.left = new Node(7);
head.right.left.left = new Node(6);
head.right.right = new Node(10);
head.right.right.left = new Node(9);
head.right.right.right = new Node(11);
preOrder(head);
System.out.println();
preOrderUnRecur(head);
}