二叉树常见遍历
-
先序遍历:先根后左再右,根左右。
-
中序遍历:先左后根再右,左根右。
-
后序遍历:先左后右再根,左右根。
-
广度优先遍历:一种图算法,二叉树中一般称为层序遍历。广度优先遍历按层处理,据开始点最近的那些顶点先被处理,而最远的那些顶点最后被处理。
-
深度优先遍历:一种图算法,深度优先遍历从某个顶点v出发,依次从v的未被访问的邻接点出发,对图进行深度优先遍历,直至图中和v有路径相通的顶点都被访问。若此时图中尚有顶点未被访问,则从一个未被访问的顶点出发,重新进行深度优先遍历,直到图中所有顶点均被访问过为止。(先序、中序、后序遍历可看做深度优先遍历)
import java.util.*;
public class BinaryTree {
public static class TreeNode {
int val;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
/**
* 先序遍历(递归)
*
* @param root 节点
*/
static void dlr(TreeNode root) {
if (root != null) {
System.out.print(root.val + ", ");
dlr(root.left);
dlr(root.right);
}
}
/**
* 中序遍历(递归)
*
* @param root 节点
*/
static void ldr(TreeNode root) {
if (root != null) {
ldr(root.left);
System.out.print(root.val + ", ");
ldr(root.right);
}
}
/**
* 后序遍历(递归)
*
* @param root 节点
*/
static void lrd(TreeNode root) {
if (root != null) {
lrd(root.left);
lrd(root.right);
System.out.print(root.val + ", ");
}
}
/**
* 广度优先遍历(队列)
*
* @param root 节点
*/
static void bfs(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
List<Integer> result = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode treeNode = queue.poll();
result.add(treeNode.val);
if (treeNode.left != null) {
queue.add(treeNode.left);
}
if (treeNode.right != null) {
queue.add(treeNode.right);
}
}
System.out.println(result);
}
/**
* 深度优先遍历(栈)
*
* @param root 节点
*/
static void dfs(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
List<Integer> result = new ArrayList<>();
while (!stack.isEmpty()) {
TreeNode treeNode = stack.pop();
result.add(treeNode.val);
if (treeNode.right != null) {
stack.push(treeNode.right);
}
if (treeNode.left != null) {
stack.push(treeNode.left);
}
}
System.out.println(result);
}
}