二叉树的遍历有前中后序遍历,以及深度优先,广度优先遍历。
public class BinaryTree {
static class Node<T> {
T value;
Node<T> left;
Node<T> right;
public Node(T value) {
this.value = value;
}
}
/**
* 前序遍历
*
* 先序遍历顺序为根、左、右
*
* @param node
*/
public static void preOrderRecur(Node node) {
if(node == null) return;
System.out.print(node.value + " ");
preOrderRecur(node.left);
preOrderRecur(node.right);
}
/**
* 中序遍历
*
* @param node
*/
public static void inOrderRecur(Node node) {
if(node == null) return;
inOrderRecur(node.left);
System.out.print(node.value + " ");
inOrderRecur(node.right);
}
/**
* 中序遍历(迭代)
*
* @param node
*/
public static void inorderTraversal(Node node) {
if (node== null) {
return;
}
Stack<node> stack = new Stack<>();
Node cur = node;
while (!stack.isEmpty() || cur != null) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
} else {
Node node = stack.pop();
System.out.println("value:" + node.value);
cur = cur.right;
}
}
}
/** 后序遍历
*
* @param node
*/
public static void lastOrderRecur(Node node) {
if(node == null) return;
lastOrderRecur(node.right);
lastOrderRecur(node.left);
System.out.print(node.value + " ");
}
/**
* 后序遍历(迭代)
*
* @param node
*/
public static void lastOrderTraversal(Node node) {
if (node == null) {
return;
}
Stack<Node> s = new Stack<>();
Stack<Node> output = new Stack<>();
s.push(node);
while (!s.isEmpty()) {
Node cur = s.pop();
output.push(cur);
if (cur.left != null) {
s.push(cur.left);
}
if (cur.right != null) {
s.push(cur.right);
}
}
while (!output.isEmpty()) {
System.out.print("value:" + output.pop().value);
}
}
/**
* 深度优先遍历,相当于前序遍历
* 采用非递归实现
* 需要辅助数据结构:栈
*
* @param node
*/
public static void depthOrderTraversal(Node node) {
if(node == null) {
System.out.println("Empty tree");
return;
}
Stack<Node> stack = new Stack<Node>();
stack.push(node);
while(!stack.isEmpty()) {
Node temp = stack.pop();
System.out.print(temp.value + " ");
if(temp.right != null) {
stack.push(temp.right);
}
if(temp.left != null) {
stack.push(temp.left);
}
}
}
/**
* 广度优先遍历
* 采用非递归实现
* 需要辅助数据结构:队列
*
* @param node
*/
public static void levelOrderTraversal(Node node) {
if(node == null) {
System.out.println("Empty tree");
return;
}
Queue<Node> queue = new LinkedList<Node>();
queue.add(node);
while(!queue.isEmpty()) {
Node temp = queue.poll();
System.out.print(temp.value + " ");
if(temp.left != null) {
queue.add(temp.left);
}
if(temp.right != null) {
queue.add(temp.right);
}
}
}
}
测试结果: