左程云基础班——二叉树
1. 遍历二叉树
二叉树结点:
public class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
1)前序遍历
public static void preOrderRecur(Node head) {
if (head == null) {
return;
}
System.out.print(head.value + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
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);
}
}
}
}
2)后序遍历
public static void postOrderRecur(Node head) {
if (head == null) {
return;
}
postOrderRecur(head.left);
postOrderRecur(head.right);
System.out.print(head.value + " ");
}
public static void postOrderUnRrecur(Node head) {
if (head != null) {
Stack<Node> stack = new Stack<>();
Stack<Node> res = new Stack<>();
stack.push(head);
while (!stack.isEmpty()) {
head = stack.pop();
res.push(head);
if (head.left != null) {
stack.push(head.left);
}
if (head.right != null) {
stack.push(head.right);
}
}
while (!res.isEmpty()) {
System.out.print(res.pop().value + " ");
}
}
}
3)中序遍历
public static void inOrderRecur(Node head) {
if (head == null) {
r