二叉树的先中后序遍历 层次遍历 Java实现
二叉树按层遍历的思路:
- 将root节点,放入队列中(先进先出),然后取出root节点,检查左节点是否为null,不为null,放入队列中,
- 检查右节点是否为null,不为null,放入队列中,然后打印root节点的值,再从队列中取出下一节点,循环直到队列为空
import java.util.LinkedList;
public class Tree {
public static void main(String[] args) {
Node root = new Node("A");
root.left = new Node("B");
root.right = new Node("C");
root.left.left = new Node("D");
root.left.right = new Node("E");
root.right.left = new Node("F");
root.right.right = new Node("G");
traversal(root);
System.out.println();
System.out.println("先序遍历:");
firstOrder(root);
System.out.println();
System.out.println("中序遍历:");
midOrder(root);
System.out.println();
System.out.println("后序遍历:");
lastOrder(root);
}
public static void firstOrder(Node root){
if (root == null) return;
System.out.print(root.value + " ");
firstOrder(root.left);
firstOrder(root.right);
}
public static void midOrder(Node root){
if (root == null) return;
midOrder(root.left);
System.out.print(root.value + " ");
midOrder(root.right);
}
public static void lastOrder(Node root){
if (root == null) return;
lastOrder(root.left);
lastOrder(root.right);
System.out.print(root.value + " ");
}
public static void traversal(Node root){
System.out.println("二叉树层次遍历");
LinkedList<Node> list = new LinkedList<>();
list.add(root);
while (! list.isEmpty()){
Node tmp = list.pop();
if (tmp.left != null){
list.offer(tmp.left);
}
if (tmp.right != null){
list.offer(tmp.right);
}
System.out.print(tmp.value + " ");
}
}
static class Node{
String value;
Node left;
Node right;
public Node(String value){
this.value = value;
}
}
}