【数据结构】二叉树的前/中/后序遍历
前序遍历
递归实现
//递归实现前序遍历
public static void PreOrderRecur(Node head) {
if (head == null) {
return;
}
System.out.println(head);
PreOrderRecur(head.left);
PreOrderRecur(head.right);
}
非递归实现
//非递归实现前序遍历
public static void PreOrderUnRecur(Node head) {
if (head == null) {
return;
}
Stack<Node> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()) {
head = stack.pop();
System.out.println(head.value);
if (head.left != null) {
stack.push(head.right);
}
if (head.right != null) {
stack.push(head.left);
}
}
}
中序遍历
递归实现
//递归实现中序遍历
public static void InOrderRecur(Node head) {
if (head == null) {
return;
}
InOrderRecur(head.left);
System.out.println(head);
InOrderRecur(head.right);
}
非递归实现
//非递归实现中序遍历
public static void InOrderUnRecur(Node head) {
if (head == null) {
return;
}
Stack<Node> stack = new Stack<>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.println(head);
head = head.right;
}
}
}
后序遍历
递归实现
//递归实现后序遍历
public static void PosOrderRecur(Node head) {
if (head == null) {
return;
}
PosOrderRecur(head.left);
PosOrderRecur(head.right);
System.out.println(head);
}
非递归实现
//非递归实现后序遍历
public static void PosOrderUnRecur(Node head) {
if (head == null) {
return;
}
//若按先左孩子进栈,再右孩子进栈,出栈的次序是头右左,所以再用一个栈就可实现左右头后序遍历
Stack<Node> stack = new Stack<>();
Stack<Node> printStack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()) {
head = stack.pop();
printStack.push(head);
if (head.left != null) {
stack.push(head.left);
}
if (head.right != null) {
stack.push(head.right);
}
}
while (!printStack.isEmpty()) {
System.out.println(printStack.pop().value);
}
}
本文来自博客园,作者:hzyuan,转载请注明原文链接:https://www.cnblogs.com/hzyuan/p/15832212.html

浙公网安备 33010602011771号