Description
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.
A leaf is a node with no children.
Given binary tree [3,9,20,null,null,15,7],
return its minimum depth = 2.
Solution
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | func minDepth(root *TreeNode) int {switch {
 
 case root == nil:
 return 0
 
 case root.Left == nil:
 return minDepth(root.Right) + 1
 
 case root.Right == nil:
 return minDepth(root.Left) + 1
 
 default:
 return min(minDepth(root.Left), minDepth(root.Right)) + 1
 }
 }
 
 func min(a, b int) int {
 if a < b {
 return a
 }
 
 return b
 }
 
 | 
Note
假設有以下參數:
說明:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | 樹的形狀如下:
 --------------------
 2
 /   \
 1     5
 /
 4
 --------------------
 
 節點 4,左節點為空,返回 1(右節點的階層加 1)。
 
 節點 5,右節點為空,返回 2(左節點的階層加 1)。
 
 節點 1,左節點為空,返回 1(右節點的階層加 1)。
 
 節點 2,比較左右節點,返回 2(兩節點較小的階層加 1)。
 
 最終返回:2
 
 | 
Code