先序遍历(先根遍历):首先访问根结点然后遍历左子树,最后遍历右子树。在遍历左、右子树时,仍然先访问根结点,然后遍历左子树,最后遍历右子树。
中序遍历:首先遍历左子树,然后访问根结点,最后遍历右子树。在遍历左、右子树时,仍然先遍历左子树,再访问根结点,最后遍历右子树。
后序遍历:后序遍历首先遍历左子树,然后遍历右子树,最后访问根结点,在遍历左、右子树时,仍然先遍历左子树,然后遍历右子树,最后遍历根结点。
定义并构造二叉树如下:
public class BinaryTree {
int root; // 根节点
BinaryTree left; // 左子树
BinaryTree right; // 右子树
public BinaryTree(int root) {
this.root = root;
left = null;
right = null;
}
//递归构造二叉树,左节点小于根节点,右节点大于根节点
public void builTree(BinaryTree tree, int root) {
if (root > tree.root) {
if (tree.right == null) {
tree.right = new BinaryTree(root);
} else {
this.builTree(tree.right, root);
}
} else {
if (tree.left == null) {
tree.left = new BinaryTree(root);
} else {
this.builTree(tree.left, root);
}
}
}
}
实例化二叉树并遍历:
public class BinaryTreePreorder {
public static void main(String[] str) {
int[] array = { 5, 3, 2, 1, 4, 8, 7, 6, 10, 9 };
BinaryTree tree = new BinaryTree(array[0]); // 创建二叉树,初始化根节点
for (int i = 1; i < array.length; i++) {
tree.builTree(tree, array[i]); // 构造二叉树
}
System.out.println("先根遍历:");
preOrder(tree);
System.out.println();
System.out.println("中根遍历:");
inOrder(tree);
System.out.println();
System.out.println("后根遍历:");
postOrder(tree);
}
public static void preOrder(BinaryTree tree) { // 先序遍历
if (tree != null) {
System.out.print(tree.root + "-");
preOrder(tree.left);
preOrder(tree.right);
}
}
public static void inOrder(BinaryTree tree) { // 中序遍历
if (tree != null) {
inOrder(tree.left);
System.out.print(tree.root + "-");
inOrder(tree.right);
}
}
public static void postOrder(BinaryTree tree) { // 后序遍历
if (tree != null) {
postOrder(tree.left);
postOrder(tree.right);
System.out.print(tree.root + "-");
}
}
}
二叉树的结构如下:
输出结果如下: