攻不下dfs不参加比赛(七)

179 阅读2分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

为什么练dfs

相信学过数据结构的朋友都知道dfs(深度优先搜索)是里面相当重要的一种搜索算法,可能直接说大家感受不到有条件的大家可以去看看一些算法比赛。这些比赛中每一届或多或少都会牵扯到dfs,可能提到dfs大家都知道但是我们为了避免眼高手低有的东西看着自己很明白就是写不出来。为了避免这种尴尬我们这几天乘着这个活动练练,好了我们话不多说开始肥学。

题目

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

示例 1: 在这里插入图片描述

输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

思路:对于每一个非叶子节点,我们只需要分别计算其左右子树的最小叶子节点深度。这样就将一个大问题转化为了小问题,可以递归地解决该问题。

解一:自下而上解法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int check(TreeNode root){
        if(root==null)return 0;
        if(root.left==null&&root.right==null)return 1;//用来判断是不是叶子节点
        int min=Integer.MAX_VALUE;//接下来就满足了如果节点没有左叶子或者右叶子就返回有叶子节点的长度
        if(root.left!=null){
            min=Math.min(check(root.left),min);
        }
        if(root.right!=null){
            min=Math.min(check(root.right),min);
        }
        return min+1;
    }
    public int minDepth(TreeNode root) {
        return check(root);
    }
}

解二:自上而下解法(稍快)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        helper(root, 1);
        return min;
    }
    int min = Integer.MAX_VALUE;
    public void helper(TreeNode root, int deep) {
        if (root == null) return;
        if (deep >= min) return;//剪枝
        if (root.left == null && root.right == null) min = Math.min(min, deep);
        helper(root.left, deep + 1);
        helper(root.right, deep + 1);
    }
}

总结

今天到这里大家应该学会了两种DFS了就是所谓的自下而上和自上而下,不同的题不同的条件选择的方式也有不同,大家可以自己体会一下。