leetcode:minimum-depth-of-binary-tree

题目: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.

翻译:

给定一个二叉树,找到其最小深度。最小深度是从根节点到最近叶节点的最短路径的节点数。

解题思路:要找二叉树最小深度,那么只要判断根节点左右两边的子树的最小深度,然后又可以把左右子树在分成左右子树,依次类推就可以把问题分解。运用递归,每次递归一次就加一,直到找到叶节点。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {
        if(root == null)
            return 0;
        int l = run(root.left);
        int r = run(root.right);
        if(l==0 || r==0)
            return 1+l+r;
        return 1+Math.min(l,r);
    }
}

注意:本题要注意最小深度与最大深度的区别:对于最大深度,不需要考虑当前子树是否为单子树(即一侧子树深度为0)的情况,即最大深度一直等于左右子树的最大值;对于最小深度,需要考虑当前子树是否为单子树的情况,对于双子树,其最小深度为左右子树的最小值,对于单子树,其最小深度为左右深度的最大值(因为有一侧的子树为0)。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容