二叉树遍历——递归与非递归实现
描述
实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式。
分析
使用递归实现二叉树遍历十分容易。在递归过程中,系统自动帮你压栈从而回溯时,关键信息不会被丢失。而非递归实现二叉树遍历时,无法再依赖系统提供的栈。你只能自己去决定压栈出栈的策略来完成非递归版本的遍历。
递归版本的二叉树遍历
设计
使用递归时二叉树每个节点都会被遍历三次。
递归访问二叉树:
// 递归遍历
void vistNode(Node node) {
if (node == null)
return;
visitNode(node);
visitNode(node);
}
遍历顺序:
1 2 4 null 4 null 4 2 5 null 5 null 5 2 1 3 6 null 6 null 6 3 null 3 1
某个数第一次被遍历到时访问它,得到的序列就是先序遍历这颗二叉树的序列:1 2 4 5 3 6
某个数第二次被遍历到时访问它,得到的序列就是中序遍历这颗二叉树的序列:4 2 5 1 6 3
某个数第三次被遍历到时访问它,得到的序列就是后序遍历这颗二叉树的序列:4 5 2 6 3 1
代码
public class BinaryTreeTraversal {
// 先序遍历
public static void preorderRecursion(Node node) {
if (node == null)
return;
System.out.print(node.element + " ");
preorderRecursion(node.left);
preorderRecursion(node.right);
}
// 中序遍历
public static void inorderRecursion(Node node) {
if (node == null)
return;
inorderRecursion(node.left);
System.out.print(node.element + " ");
inorderRecursion(node.right);
}
// 后序遍历
public static void postorderRecursion(Node node) {
if (node == null)
return;
postorderRecursion(node.left);
postorderRecursion(node.right);
System.out.print(node.element + " ");
}
public static void main(String[] args) {
Node tree = new Node(1);
tree.left = new Node(2);
tree.right = new Node(3);
tree.left.left = new Node(4);
tree.left.right = new Node(5);
tree.right.left = new Node(6);
System.out.print<