Tree - 111. Minimum Depth of Binary Tree

时间:2022-07-25
本文章向大家介绍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
    
}