LeetCode66|二叉树的最小深度

时间:2022-07-26
本文章向大家介绍LeetCode66|二叉树的最小深度,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,问题简述

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

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

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

2,示例

示例:

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

    3
   / 
  9  20
    /  
   15   7
返回它的最小深度  2.

 

3,题解思路

递归的使用

4,题解程序


public class MinDepthTest {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(3);
        TreeNode t2 = new TreeNode(9);
        TreeNode t3 = new TreeNode(20);
        TreeNode t4 = new TreeNode(15);
        TreeNode t5 = new TreeNode(7);
        t1.left = t2;
        t1.right = t3;
        t3.left = t4.left;
        t3.right = t5;
        int depth = minDepth(t1);
        System.out.println("depth = " + depth);

    }

    public static int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        Integer minValue = Integer.MAX_VALUE;
        if (root.left != null) {
            minValue = Math.min(minDepth(root.left), minValue);
        }
        if (root.right != null) {
            minValue = Math.min(minDepth(root.right), minValue);
        }
        return minValue + 1;
    }
}

5,题解程序图片版

6,总结

递归的使用