递归序
每个节点都会 来到 三次 然后根据在每次来的时候,在哪一次操作,分为三种遍历,都是基于根节点为参考
- 先序, 头 左 右
- 中序, 左 头 右
- 后序, 左 右 头
递归实现
public static class Node {
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
}
public static void preOrderRecur(Node head) {
if (head == null) {
return;
}
// 1
System.out.println(head.value + " ");
preOrderRecur(head.left);
// 2
preOrderRecur(head.right);
// 3
}
public static void inOrderRecur(Node head) {
if (head == null) {
return;
}
// 1
inOrderRecur(head.left);
// 2
System.out.println(head.value + " ");
inOrderRecur(head.right);
// 3
}
public static void postOrderRecur(Node head) {
if (head == null) {
return;
}
// 1
postOrderRecur(head.left);
// 2
postOrderRecur(head.right);
// 3
System.out.println(head.value + " ");
}
所有递归都可以改为非递归
先序,非递归
准备一个栈,先把根节点压栈,
开始弹,直到栈为空,弹出来就打印(处理)
如果右节点存在,就先压右节点
如果左节点存在,就后压左节点
public static void preOrderUnRecur(Node head) {
if (head == null) {
return;
}
// 先序 非递归实现
// 需要一个栈,
Stack<Node> stack = new Stack<>();
// 先把 头节点压进去
stack.push(head);
Node cur = null;
while (!stack.empty()) {
// 弹出
cur = stack.pop();
// 打印处理
System.out.print(cur.value + " ");
// 先压右
if (cur.right != null) {
stack.push(cur.right);
}
// 再压左
if (cur.left != null) {
stack.push(cur.left);
}
}
}
后序遍历 ,非递归
后序遍历和先序遍历,需要再借助一个栈2
先把头压进栈1,开始弹,弹出来,先不处理,然后压入栈2.
如果有左节点,先压左节点进栈1
如果有右节点,后压右节点进栈1
这样栈1 入栈是头 左 右 , 出栈是 头 右 左
栈2 入栈是 头 右 左, 出栈是 左右头。(左右头就是 后序)
全部完毕之后,栈2依次出栈
public static void postOrderUnRecur(Node head) {
if (head == null) {
return;
}
Stack<Node> stack1 = new Stack<>();
Stack<Node> stack2 = new Stack<>();
Node cur = null;
stack1.push(head);
while (!stack1.empty()) {
cur = stack1.pop();
stack2.push(cur);
if (cur.left != null) {
stack1.push(cur.left);
}
if (cur.right != null) {
stack1.push(cur.right);
}
}
while (!stack2.empty()) {
System.out.print(stack2.pop().value + " ");
}
}
中序遍历,非递归
1:左节点 全部入栈,直到左节点为null,
2:开始弹出,打印处理节点,如果有右节点,重复1,2,
3: 如果没有 右节点,走弹出,
public static void inOrderUnRecur(Node head) {
if (head == null) {
return;
}
Stack<Node> stack = new Stack<>();
while (!stack.empty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}