l111 minimum depth of binary tree

题目描述

1
2
3
4
5
6
7
8
9
10
11

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.

Example:
1
/
2
Output:
2

解题思路

104题目的解题思路相同

不同的是将depth设置为一个比较大的数,和level+1进行比较,如果出现更小的就替换。

Go实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
func (root *TreeNode, depth *int, level int)  {
if root==nil {
return
}

if root.Left == nil && root.Right==nil {
if *depth>level+1 {
*depth = level+1
}
return
}

travel(root.Left, depth, level+1)
travel(root.Right, depth, level+1)
}

func minDepth(root *TreeNode) int {
if root == nil {
return 0
}

var depth int
depth=10000
travel(root, &depth, 0)
return depth
}