题解 | #牛群的最短路径#
牛群的最短路径
https://www.nowcoder.com/practice/c07472106bfe430b8e2f55125d817358?tpId=354&tqId=10591753&ru=/exam/oj/ta&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D354
知识点:
dfs
解题思路:
深度优先遍历,遍历是利用参数计算深度。当节点左右节点都为空时说明是叶子节点,更新res
语言:
Golang
package main import ( "math" ) /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ func minDepth( root *TreeNode ) int { // write code here if root == nil{ return 0 } res:=math.MaxInt32 var dfs func(root *TreeNode,depth int) dfs = func(root *TreeNode, depth int) { if root.Left==nil && root.Right == nil{ if res > depth{ res = depth } return } if root.Left!=nil{ dfs(root.Left,depth+1) } if root.Right!=nil{ dfs(root.Right,depth+1) } } dfs(root,1) return res }