二叉树是一种很常见的数据结构,其结构如下图:
下面接受他的四种遍历方式:
- 先序(先根)遍历:即先访问根节点,再访问左孩子和右孩子
- 中序遍历:
- 后序遍历:
- 层次遍历:按照所在层数,从下往上遍历
前提:这里先给出测试中的二叉树结构,如下图所示
该二叉树对应的几种遍历方式的结果顺序:
先序遍历:10->6->4->8->14->12->16
中序遍历:4->6->8->10->12->14->16
后序遍历:4->8->6->12->16->14->10
层次遍历:10->6->14->4->8->12->16
接下来是相应的代码实现:
public class Main {
public static void main(String[] args) {
TreeNode root = initTreeNode();
levelIterator(root);
// PreNode(root);
// InNode(root);
// ProNode(root);
}
/**
* 层次遍历
* @param root 根结点
*/
public static void levelIterator(TreeNode root) {
if (root == null) {
return;
}
LinkedList<TreeNode> queue = new LinkedList<>();
TreeNode current = null;
queue.offer(root);//进队
while (!queue.isEmpty()) {
current = queue.poll();//出队
System.out.print(current.val + "->");
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}
}
/**
* 先序遍历
* @param root 根结点
*/
public static void PreNode(TreeNode root) {
if (root != null) {
System.out.print(root.val + "->");
PreNode(root.left);
PreNode(root.right);
}
}
/**
* 中序遍历
* @param root 根结点
*/
public static void InNode(TreeNode root) {
if (root != null) {
InNode(root.left);
System.out.print(root.val + "->");
InNode(root.right);
}
}
/**
* 后序遍历
* @param root
*/
public static void ProNode(TreeNode root) {
if (root != null) {
ProNode(root.left);
ProNode(root.right);
System.out.print(root.val + "->");
}
}
/**
* 初始化二叉树
* @return 二叉树的根结点
*/
public static TreeNode initTreeNode() {
TreeNode root = new TreeNode(10);
root.left = new TreeNode(6);
root.right = new TreeNode(14);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(8);
root.right.left = new TreeNode(12);
root.right.right = new TreeNode(16);
return root;
}
/**
* 二叉树的数据结构
*/
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}
对于前、中、后序遍历,使用的是递归的思想,按照其先后顺序输出即可实现。
层次遍历则是使用到了队列,具体过程用一张图表示。