📑 题目:111. 二叉树的最小深度

🚀 本题 LeetCode 传送门

题目大意

给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。说明: 叶子节点是指没有子节点的节点。

解题思路

  • 递归求出根节点到叶子节点的深度,输出最小值即可

代码

  1. package leetcode
  2. /**
  3. * Definition for a binary tree node.
  4. * type TreeNode struct {
  5. * Val int
  6. * Left *TreeNode
  7. * Right *TreeNode
  8. * }
  9. */
  10. func minDepth(root *TreeNode) int {
  11. if root == nil {
  12. return 0
  13. }
  14. if root.Left == nil {
  15. return minDepth(root.Right) + 1
  16. }
  17. if root.Right == nil {
  18. return minDepth(root.Left) + 1
  19. }
  20. return min(minDepth(root.Left), minDepth(root.Right)) + 1
  21. }