爱程序网

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.

思路:

递归,注意是到leaf node,所以有一个孩子为空的话,则取非空的那一孩子

package tree;

public class MinimumDepthOfBinaryTree {
    
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null || root.right == null) return root.left == null ? (1 + minDepth(root.right)) : (1 + minDepth(root.left));
        return Math.min(1 + minDepth(root.left), 1 + minDepth(root.right));
    }
    
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助