Java针对二叉树的几种遍历方式
package binarytree.create;
import java.util.ArrayDeque;
import java.util.Queue;
/**
* 二叉树的创建与遍历
* @date 2018-07-02 14:34:32
*/
public class BinaryTreeCreate {
public static void main(String[] args) {
TreeNode node = createNode();
// 遍历
// 二叉树前序遍历
preorder(node);
// 中序遍历
centOrder(node);
// 后序遍历
followOrder(node);
// 层次遍历
levelOrder(node);
}
/**
* 1
* / \
* 2 3
* / \ / \
* 4 5 6 7
* @return
*/
private static TreeNode createNode() {
TreeNode root = new TreeNode(1); // 树根
TreeNode nleft = new TreeNode(2); // 左节点
TreeNode nright = new TreeNode(3); // 右节点
TreeNode lnleft = new TreeNode(4); // 左节点
TreeNode lnright = new TreeNode(5); // 右节点
nleft.setLeftNode(lnleft);
nleft.setRightNode(lnright);
TreeNode rnleft = new TreeNode(6); // 左节点
TreeNode rnright = new TreeNode(7); // 右节点
nright.setLeftNode(rnleft);
nright.setRightNode(rnright);
root.setLeftNode(nleft);
root.setRightNode(nright);
return root;
}
/**
* 二叉树前序遍历
* 根节点 -> 左子树 -> 右子树
* @param root
*/
public static void preorder(TreeNode root) {
if (root != null) {
System.out.println(root.getVal());
preorder(root.getLeftNode());
preorder(root.getRightNode());
}
}
/**
* 二叉树中序遍历
* 左子树 -> 根节点 -> 右子树
* @param root
*/
public static void centOrder(TreeNode root) {
if (root != null) {
centOrder(root.getLeftNode());
System.out.println(root.getVal());
centOrder(root.getRightNode());
}
}
/**
* 二叉树后序遍历
* 左字树 -> 右子树 -> 根节点
* @param root
*/
public static void followOrder(TreeNode root) {
if (root != null) {
followOrder(root.getLeftNode());
followOrder(root.getRightNode());
System.out.println(root.getVal());
}
}
/**
* 二叉树层次遍历
* 从上至下->从左到右
* @param root
*/
public static void levelOrder(TreeNode root){
Queue<TreeNode> quue = new ArrayDeque();
quue.offer(root); // 入队
while (!quue.isEmpty()) {
TreeNode node = quue.poll(); // 出队
System.out.println(node.getVal());
if (node.getLeftNode() != null) {
quue.offer(node.getLeftNode());
}
if (node.getRightNode() != null) {
quue.offer(node.getRightNode());
}
}
}
}