算法笔记 码 码 不停蹄
1、递归法遍历二叉树
1)递归法访问二叉树的顺序
-
访问顺序依次为:A-B-D-D-D-B-E-E-E-B-A-C-F-F-F-C-G-G-G-C-A
-
原因:先访问【A】;再访问A左,是【B】;再访问B左,是【D】;再访问D左,是空,则返回到【D】;再访问D右,是空,则返回到【D】;返回到【B】;访问B右,是【E】;访问E左,是空,则返回到【E】;访问E右,是空,则返回到【E】;返回到【B】;再返回到【A】;访问A右,是【C】;访问C左,是【F】;访问F左,是空,则返回到【F】;访问F右,是空,则返回到【F】;返回到【C】;访问C右,是【G】;访问G左,是空,则返回到【G】;再访问G右,是空,则返回到【G】;返回到【C】;返回到【A】;
2)前序遍历:
3)中序遍历:
4)后续遍历:
2、非递归遍历二叉树
2)前序遍历:
public static void preOrderUnRecur(Node head) {
System.out.print("pre-order: ");
if (head != null) {
Stack<Node> stack = new Stack<Node>();
stack.add(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();
}
3)中序遍历:
public static void inOrderUnRecur(Node head) {
System.out.print("in-order: ");
if (head != null) {
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}
System.out.println();
}
4)后续遍历:
- 思想:和非递归前序方法几乎相同。只是在前序中需要打印的时候,把这些数存放到另外一个栈中,循环结束的时候再打印这个另外的栈,实现非递归前序栈的”先中再右再左“的逆序,即”先左再右再中“
public static void posOrderUnRecur1(Node head) {
System.out.print("pos-order: ");
if (head != null) {
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.push(head);
while (!s1.isEmpty()) {
head = s1.pop();
s2.push(head);
if (head.left != null) {
s1.push(head.left);
}
if (head.right != null) {
s1.push(head.right);
}
}
while (!s2.isEmpty()) {
System.out.print(s2.pop().value + " ");
}
}
System.out.println();
}
1417

被折叠的 条评论
为什么被折叠?



