前序
先遍历根节点,在左子节点,在右子节点
中序
先遍历左子节点,在根节点,在右子节点
后序
先变量左子节点,在右子节点,在根节点
代码
package BinaryTree;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;
/**
* @author iu
*/
public class PrintBinaryTree {
// 先序遍历 递归实现
public static void frontPrintBinaryTree(BinaryTreeNode binaryTreeNode) {
if (binaryTreeNode != null) {
System.out.print(binaryTreeNode.value + "\t");
frontPrintBinaryTree(binaryTreeNode.leftNode);
frontPrintBinaryTree(binaryTreeNode.rightNode);
}
}
//先序遍历 循环实现
public static void frontPrintBinaryTreeLoop(BinaryTreeNode binaryTreeNode) {
Stack<BinaryTreeNode> stack = new Stack();
if (stack.isEmpty() && binaryTreeNode != null) {
stack.push(binaryTreeNode);
}
while (!stack.isEmpty()) {
BinaryTreeNode pop = stack.pop();
System.out.print(pop.value + "\t");
//右节点先入栈,左节点后入栈
if (pop.rightNode != null) {
stack.push(pop.rightNode);
}
if (pop.leftNode != null) {
stack.push(pop.leftNode);
}
}
}
//中序遍历 递归
public static void middlePrintBinaryTree(BinaryTreeNode binaryTreeNode) {
if (binaryTreeNode != null) {
middlePrintBinaryTree(binaryTreeNode.leftNode);
System.out.print(binaryTreeNode.value + "\t");
middlePrintBinaryTree(binaryTreeNode.rightNode);
}
}
//中序遍历 循环实现
public static void middlePrintBinaryTreeLoop(BinaryTreeNode binaryTreeNode) {
Stack<BinaryTreeNode> stack = new Stack<>();
while (binaryTreeNode != null || !stack.isEmpty()) {
while (binaryTreeNode != null) {
stack.push(binaryTreeNode);
binaryTreeNode = binaryTreeNode.leftNode;
}
if (!stack.isEmpty()) {
BinaryTreeNode pop = stack.pop();
System.out.print(pop.value+ "\t");
binaryTreeNode = pop.rightNode;
}
}
}
//后序遍历 递归实现
public static void backPrintBinaryTree(BinaryTreeNode binaryTreeNode) {
if (binaryTreeNode != null) {
backPrintBinaryTree(binaryTreeNode.leftNode);
backPrintBinaryTree(binaryTreeNode.rightNode);
System.out.print(binaryTreeNode.value + "\t");
}
}
//层次遍历
public static void layerPrintBinaryTree(BinaryTreeNode binaryTreeNode) {
if (binaryTreeNode == null) {
return;
}
Deque<BinaryTreeNode> deque = new ArrayDeque();
deque.add(binaryTreeNode);
while (deque.size() > 0) {
BinaryTreeNode node = deque.getFirst();
System.out.println(deque.pop().value);
if (node.leftNode != null) {
deque.add(node.leftNode);
}
if (node.rightNode != null) {
deque.add(node.rightNode);
}
}
}
}