深度优先遍历(depth first dearch 简称:DFS)和广度优先遍历(breath first dearch简称:BFS)是两种重要的算法。
深度优先遍历:
主要思路就是从一个未访问的结点出发,一路走到底,然后从这条路尽头的节点回退到上一个节点,再从另一条路开始走到底...,不断递归重复此过程,直到所有的顶点都遍历完成,它的特点是不撞南墙不回头,先走完一条路,再换一条路继续走。
我们以二叉树为例,实现一下深度遍历
(递归用法):
public class Solution{
privait static class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(){}
public TreeNode(int val) { this.val = val}
public TreeNode(int val,TreeNode left,TreeNode right){
this.val = val ;
this.left = left;
this.right = right;
}
}
public static void dfs(TreeNode Node){
if(Node == null){
return ;
}
process(Node);
dfs(Node.left);
dfs(Node.right);
}
}
(非递归用法):
public static void dfsWithStack(Node root) {
if (root == null) {
return;
}
Queue<Node> stack = new LinkedList<>();
stack.add(root);
while (!stack.isEmpty()) {
Node node = stack.poll();
System.out.println("value = " + node.value);
Node left = node.left;
if (left != null) {
stack.add(left);
}
Node right = node.right;
if (right != null) {
stack.add(right);
}
}
}
广度优先遍历:
广度优先遍历,主要思路是从图的一个未遍历的节点出发,先遍历这个节点的相邻节点,再依次遍历每个相邻节点的相邻节点。
以二叉树为例:
private static void bfs(Node root) {
if (root == null) {
return;
}
Queue<Node> stack = new LinkedList<>();
stack.add(root);
while (!stack.isEmpty()) {
Node node = stack.poll();
System.out.println("value = " + node.value);
Node left = node.left;
if (left != null) {
stack.add(left);
}
Node right = node.right;
if (right != null) {
stack.add(right);
}
}
}