LeetCode - Minimum Depth of Binary Tree

时间:2021-07-04 08:09:17

题目:

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));
} }