二叉树的遍历主要分三种,分别是先序、中序、后序。
如果按搜索的话可分为bfs(广度优先搜索)和dfs(深度优先搜索),前者基于队列后者基于栈,在处理树和图的时候比较常用。
再来说先序、中序、后序三种遍历的区别:
- 先序 父->左->右
- 中序 左->父->右
- 后序 左->右->父
如果使用递归很简单,我们可以使用递归栈的特性,轻松实现树的先中后序遍历,如下
//先序
private static void pre(Node root) {
System.out.println(root.val);
if(root.left != null) {
pre(root.left);
}
if(root.right != null) {
pre(root.right);
}
}
//中序
private static void mid(Node root) {
if(root.left != null) {
mid(root.left);
}
System.out.println(root.val);
if(root.right != null) {
mid(root.right);
}
}
//后序
private static void after(Node root) {
if(root.left != null) {
after(root.left);
}
if(root.right != null) {
after(root.right);
}
System.out.println(root.val);
}
很容易发现三种遍历方式的区别只是打印当前节点的这样代码位置的变动,几行代码就能轻松实现;
而要是使用非递归呢,因为上面代码是利用的递归的特性,即栈。那么不实用递归我们就需要自己来维护一个栈。
先序
其实while循环里面的语句跟非递归先序遍历的代码类似,只是我们需要手动维护栈。
//先序
private static void pre(Node root) {
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node node = stack.pop();
System.out.println(node.val);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
}
中序
//中序
private static void mid(Node root) {
Stack<Node> stack = new Stack<>();
Node node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
System.out.println(node.val);
node = node.right;
}
}
后序
后序的非递归实现本身比较麻烦,但是在做leetcode的时候看到了这个方法比较巧,巧在灵活运用了链表头插尾删这些特点(讲真,之前不知道LinkedList有pollLast和addFirst方法)。这样写出来感觉跟先序遍历差不多,但是要注意链表插节点和取节点的位置,理解着记忆。
// 后序
private static void after(Node root) {
LinkedList<Node> stack = new LinkedList<>();
LinkedList<Integer> output = new LinkedList<>();
stack.add(root);
while (!stack.isEmpty()) {
Node node = stack.pollLast();
output.addFirst(node.val);
if (node.left != null) {
stack.add(node.left);
}
if (node.right != null) {
stack.add(node.right);
}
}
System.out.println(output);
}