二叉树的四种遍历方式:前序遍历、中序遍历、后序遍历和层序遍历
package binaryTree;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
package binaryTree;
import java.util.ArrayList;
import java.util.LinkedList;
public class BinaryTreeTraverse {
public static void main(String[] args) {
TreeNode root = new TreeNode(0);
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
root.left = node1;
root.right = node2;
node1.left = node3;
node1.right = node4;
node2.left = node5;
node2.right = node6;
// 辅助队列
LinkedList<TreeNode> helper = new LinkedList<TreeNode>();
ArrayList<Integer> list = new ArrayList<Integer>();
preOrderTraverse(root,list);
System.out.println("前序遍历"+list);
list.clear();
inOrderTraverse(root,list);
System.out.println("中序遍历"+list);
list.clear();
postOrderTraverse(root,list);
System.out.println("后序遍历"+list);
list.clear();
if(root!=null) {
helper.add(root);
floorOrderTraver(helper,list);
}
System.out.println("层序遍历"+list);
list.clear();
helper.clear();
}
// 前序遍历;
private static void preOrderTraverse(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
preOrderTraverse(root.left, list);
preOrderTraverse(root.right, list);
}
// 中序遍历;
private static void inOrderTraverse(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return;
}
inOrderTraverse(root.left, list);
list.add(root.val);
inOrderTraverse(root.right, list);
}
// 后序遍历;
private static void postOrderTraverse(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return;
}
postOrderTraverse(root.left, list);
postOrderTraverse(root.right, list);
list.add(root.val);
}
// 层序遍历
private static void floorOrderTraver(LinkedList<TreeNode> helper, ArrayList<Integer> list) {
while (!helper.isEmpty()) {
// 从队列中移除并返回;
TreeNode tmp = helper.pollFirst();
list.add(tmp.val);
if (tmp.left != null) {
helper.offerLast(tmp.left);
}
if (tmp.right != null) {
helper.offerLast(tmp.right);
}
}
}
}
运行结果