编号111:二叉树的最小深度

编号111:二叉树的最小深度

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

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

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

示例:

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

图片

返回它的最小深度 2.

思路

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

什么是叶子节点,左右孩子都为空的节点才是叶子节点!

递归法

遍历方式还是后续的方式;左右中;

如果左子树为空,则最小深度为1+右子树;

如果右子树为空,则最小深度为1+左子树;

层序遍历的方法

在遍历到一层的时候;如果左右子树均为空,则找到了最短的叶子结点

//递归实现
public static int minDepth1(Node root) {
        if (root == null) {
            return 0;
        }

        int leftDepth =minDepth(root.left);
        int rightDepth=minDepth(root.right);

        if (root.left == null && root.right==null){
            return 1+rightDepth;
        }

        if (root.left != null && root.right == null){
            return 1+leftDepth;
        }
        int result = 1+Math.min(leftDepth,rightDepth);
        return result;
    }
//层序遍历实现
public static int minDepth(Node root) {
        if (root == null) {
            return 0;
        }
        //层序遍历实现
        Queue<Node> queue = new ArrayDeque<>();
        queue.add(root);
        int depth = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            depth++;
            for (int i = 0; i < size; i++) {
                Node temp = queue.poll();
                if (temp.left != null) {
                    queue.add(temp.left);
                }
                if (temp.right != null) {
                    queue.add(temp.right);
                }
                //当层序遍历时,其左右结点均为空,说明找到里叶子结点 这时候就是最小深度值
                if (temp.left == null && temp.right == null) {
                    return depth;
                }
            }
        }
        return depth;
    }

posted @ 2021-04-06 15:03  胡木杨  阅读(85)  评论(0)    收藏  举报