Tree - 111. Minimum Depth of Binary Tree
111. 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:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
思路:
求二叉树的最小深度,可以采用深度优先搜索递归求解。
代码:
go:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
left, right := minDepth(root.Left), minDepth(root.Right)
if left == 0 || right == 0 {
return left + right + 1
}
if (left > right) {
return right + 1
}
return left + 1
}