深度优先搜索(DFS)算法总结
1.介绍
深度优先搜索属于图算法的一种,是一个针对图和树的遍历算法,英文缩写为DFS即Depth First Search。深度优先搜索是图论中的经典算法,利用深度优先搜索算法可以产生目标图的相应拓扑排序表,利用拓扑排序表可以方便的解决很多相关的图论问题,如最大路径问题等等。一般用堆数据结构来辅助实现DFS算法。其过程简要来说是对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次。
2.思路
- 深度优先搜索是一种遍历图或树的策略,通常使用递归或迭代(非递归 ) 的方式实现
- 只关心当前节点的状态
3.例题
3.1 LeetCode 100. 相同的树
- 思路
- 只考虑当前节点状态
- 当前节点是否为空
- 如果不为空,值是否相等
- 只考虑当前节点状态
- 代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
//递归法
// p and q are both null
if (p == null && q == null) return true;
// one of p and q is null
if (q == null || p == null) return false;
// p and q are both not null
if (p.val != q.val) return false;
return isSameTree(p.right, q.right) && isSameTree(p.left, q.left);
}
}
3.2 LeetCode 101. 对称二叉树
-
思路
- 和上一道题类似,题目可以改成:判断一个二叉树和将其反转后形成的二叉树是否相同
- 只考虑当前节点状态
-
代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
//父节点相等并且子节点对称
return (t1.val == t2.val)
&& isMirror(t1.right, t2.left)
&& isMirror(t1.left, t2.right);
}
}
3.3 LeetCode 104. 二叉树的最大深度
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
//递归实现
if(root==null){
return 0;
}else{
int left_height = maxDepth(root.left);
int right_height = maxDepth(root.right);
//比较下一层节点的左右子树深度
//+1是考虑根节点所在那一层
return java.lang.Math.max(left_height, right_height) + 1;
}
}
}