leetcode-111-easy

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.

Note: A leaf is a node with no children.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
Constraints:

The number of nodes in the tree is in the range [0, 105].
-1000 <= Node.val <= 1000

思路一:假设给定的节点不为空,那么完全分类后有四种情况

  • left == null && right == null
  • left != null && right != null
  • left == null && right != null
  • left != null && right == null

其中只有第一种情况是符合题目的叶子节点,递归判断即可

public int minDepth(TreeNode root) {
    if (root == null) return 0;
    return minDepth(root, 1);
}

public int minDepth(TreeNode root, int depth) {
     if (root.left == null && root.right == null) {
        return depth;
    } else if (root.left != null && root.right == null) {
        return minDepth(root.left, depth + 1);
     } else if (root.right != null && root.left == null) {
         return minDepth(root.right, depth + 1);
     } else {
         return Math.min(minDepth(root.left, depth + 1), minDepth(root.right, depth + 1));
     }
}

思路二:官方给的题解是从底层往上递归,代码可以更简洁

posted @ 2022-11-30 21:33  iyiluo  阅读(22)  评论(0)    收藏  举报