分别用递归和非递归实现二叉树前序、中序、后序遍历
java代码
package com.lizhouwei.chapter3;
import java.util.Stack;
/**
* @Description:分别用递归和非递归实现二叉树前序、中序、后序遍历
* @Author: lizhouwei
* @CreateDate: 2018/4/14 9:32
* @Modify by:
* @ModifyDate:
*/
public class Chapter3_1 {
//前序递归
public void recPreOrder(Node head) {
if (head == null) {
return;
}
System.out.print(head.value + " ");
recPreOrder(head.left);
recPreOrder(head.right);
}
//中序递归
public void recInOrder(Node head) {
if (head == null) {
return;
}
recInOrder(head.left);
System.out.print(head.value + " ");
recInOrder(head.right);
}
//后序递归
public void recPostOrder(Node head) {
if (head == null) {
return;
}
recPostOrder(head.left);
recPostOrder(head.right);
System.out.print(head.value + " ");
}
//------------非递归----------------//
//前序
public void preOrder(Node head) {
if (head == null) {
return;
}
Stack<Node> stack = new Stack<Node>();
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);
}
}
}
//中序
public void inOrder(Node head) {
if (head == null) {
return;
}
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;
}
}
}
//后序
public void postOrder(Node head) {
if (head == null) {
return;
}
Node cur = null;
Stack<Node> stack = new Stack<Node>();
stack.push(head);
while (!stack.isEmpty()) {
cur = stack.peek();
if (cur.left != null && cur.left != head && cur.right != head) {
stack.push(cur.left);
} else if (cur.right != null && cur.right != head) {
stack.push(cur.right);
} else {
head = stack.pop();
System.out.print(head.value + " ");
}
}
}
//测试
public static void main(String[] args) {
Chapter3_1 chapter = new Chapter3_1();
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Node head = NodeUtil.generTree(arr, 0, arr.length - 1);
//前序递归打印
System.out.print("前序递归打印:");
chapter.recPreOrder(head);
System.out.println();
//前序非递归打印
System.out.print("前序非递归打印:");
chapter.preOrder(head);
System.out.println();
System.out.println();
//中序递归打印
System.out.print("中序递归打印:");
chapter.recInOrder(head);
System.out.println();
System.out.print("中序非递归打印:");
chapter.inOrder(head);
System.out.println();
System.out.println();
//后序递归打印
System.out.print("后序递归打印:");
chapter.recPostOrder(head);
System.out.println();
System.out.print("后序非递归打印:");
chapter.postOrder(head);
}
}