Leetcode——二叉树的最小深度

Q:求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
A:
1.递归
注意,一定要是根节点到叶节点的。所以要判断根节点是否有孩子。

    public int run(TreeNode root) {
        if (root == null)
            return 0;
        int l = run(root.left);
        int r = run(root.right);
        return Math.min(l, r) + 1;
    }

2.BFS
怎么套到 BFS 的框架里呢?首先明确一下起点start和终点target是什么,怎么判断到达了终点?
显然起点就是root根节点,终点就是最靠近根节点的那个「叶子节点」嘛,叶子节点就是两个子节点都是null的节点

    public int minDepth(TreeNode root) {
        if(root == null)
            return 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int depth = 1;

        while(!q.isEmpty()){
            int sz = q.size();
            for(int i=0;i<sz;i++){
                TreeNode curr = q.poll();
                if(curr.left == null && curr.right == null)
                    return depth;
                if(curr.left!=null){
                    q.offer(curr.left);
                }
                if(curr.right!=null)
                    q.offer(curr.right);
            }
            depth++;
        }
        return depth;
    }
原文地址:https://www.cnblogs.com/xym4869/p/12422203.html