本地 IDE 树的最小深度 LeetCode111_Minimum_Depth_of_Binary_Tree

package leetCode;

public class LeetCode111_Minimum_Depth_of_Binary_Tree {


public static void main(String[] args) {
    Integer array[] = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    TreeNode binaryTreeByArry = createBinaryTreeByArry(array, 0);
    System.out.print("先根遍历:");
    preOrder(binaryTreeByArry);
    System.out.println();
    Solution solution = new Solution();
    int i = solution.minDepth(binaryTreeByArry);
    System.out.println("最小深度:" + i);


}

//定义二叉树的节点
static class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

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

}

//构造二叉树
static TreeNode createBinaryTreeByArry(Integer[] array, int index) {
    TreeNode tn = null;
    if (index < array.length) {
        Integer value = array[index];
        if (value == null) {
            return null;
        }
        tn = new TreeNode(value);
        tn.left = createBinaryTreeByArry(array, 2 * index + 1);
        tn.right = createBinaryTreeByArry(array, 2 * index + 2);

    }
    return tn;

}

//找到树的最小深度
static class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1;

    }
}

//先根遍历
static void preOrder(TreeNode treeNode) {

    if (treeNode != null) {
        System.out.print(treeNode.val + "\t");
        preOrder(treeNode.left);
        preOrder(treeNode.right);
    }
}}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42664961/article/details/83412592