日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

go語言算法題解二叉樹的最小深度_Golang

作者:tukoyi ? 更新時間: 2022-11-21 編程語言

題目:

給定一個二叉樹,找出其最小深度。

最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。

說明:

葉子節點是指沒有子節點的節點。

解法:

func minDepth(root *TreeNode) int {
	if root == nil {
		return 0
	}
	minDepth := math.MaxInt64
	var dfs func(node *TreeNode, depth int)
	dfs = func(node *TreeNode, depth int) {
		if node == nil {
			return
		}
		depth ++
		if node.Left == nil && node.Right == nil {
			if depth < minDepth {
				minDepth = depth 
			}
		}
		dfs(node.Left, depth)
		dfs(node.Right, depth)
	}
	dfs(root, 0)
	return minDepth
}

原文鏈接:https://juejin.cn/post/7152160227389866014

欄目分類
最近更新