前言

Github:https://github.com/HealerJean

博客:http://blog.healerjean.com

1、二叉树的最小深度

给定一个整型数组, 你的任务是找到所有该数组的子序列,子序列的长度至少是2。

示例:


输入: [4, 6, 7, 7]
输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]

说明:
给定数组的长度不会超过15。
数组中的整数范围是 [-100,100]。
给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。

1.1、解题思路

和最大深度基本一致,但还是有区别的

1.2、算法

public int minDepth(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(minDepth(root.left), min);
    }
    if (root.right != null) {
        min = Math.min(minDepth(root.right), min);
    }
    //最后加上自身
    return min + 1;
}

1.3、测试

@Test
public void test(){
    System.out.println(minDepth(initTreeNode()));
}

public TreeNode initTreeNode(){
    TreeNode treeNode2 = new TreeNode(2, null, null);
    TreeNode root = new TreeNode(1, treeNode2, null);
    return root ;
}

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

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

    }
}

ContactAuthor