原题链接

golang示例代码

 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * 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
    }
    length := 0
    queue := []*TreeNode{root}
    for len(queue) > 0 {
        // 树当前层的子节点数
        currNodeCnt := len(queue)
        // 将当前层的节点出队列
        for i := 0; i < currNodeCnt; i++ {
            curr := queue[0]
            // 如果当前节点左子树与右子树均为空,说明是叶子结点, + 1返回
            // 下面判断去掉,就是取最大深度了
            if curr.Left == nil && curr.Right == nil {
                return length + 1
            }
            // 当当前子结点左不为空,加入队列
            if curr.Left != nil {
                queue = append(queue, curr.Left)
            }
            // 当当前右结点不为空,加入队列
            if curr.Right != nil {
                queue = append(queue, curr.Right)
            }
            // 以上append执行完后,就是下一层的节点数了
            // 当前层的节点出队
            queue = queue[1:]
        }
        // 当上面循环执行完,说明遍历完了一层。深度+1
        length += 1
    }
    return length
}