刷爆力扣

【20】二叉树的最小深度

2021-05-10  本文已影响0人  公孙剑人

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

题目

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

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

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

示例1:

给定二叉树 [3,9,20,null,null,15,7],



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

示例 2:

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

思路

这个很容易就想到广度优先算法,我们只有一层层的取节点并判断,找到首个叶子节点,即可知道这棵树的最小深度。

代码

// 定义结构体
public class TreeNode {
    TreeNode left;
    TreeNode right;
    int depth;  // 保存当前节点深度

    TreeNode() {
    }

    TreeNode(int depth, TreeNode left, TreeNode right) {
        this.depth = depth;
        this.left = left;
        this.right = right;
    }
}

// 算法开始
    public static int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        // 根节点的深度固定设置为1
        root.depth = 1;
        while (!queue.isEmpty()) {
            // 取出队列的第一个节点
            TreeNode firstNode = queue.poll();
            // 当符合条件时,该节点的depth,就是这棵树的最小深度
            if (firstNode.left == null && firstNode.right == null) {
                return firstNode.depth;
            }
            if (firstNode.left != null) {
                // 节点深度加一
                firstNode.left.depth = firstNode.depth + 1;
                queue.offer(firstNode.left);
            }
            if (firstNode.right != null) {
                // 节点深度加一
                firstNode.right.depth = firstNode.depth + 1;
                queue.offer(firstNode.right);
            }
        }
        return 0;
    }

结果

执行结果
上一篇 下一篇

猜你喜欢

热点阅读