BFS
LC 111. Minimum Depth of Binary Tree
https://leetcode.com/problems/minimum-depth-of-binary-tree/
DFS 解法
Code Block |
---|
|
/**
* 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
}
return dfs(root)
}
func dfs(root *TreeNode) int {
if root.Left == nil && root.Right == nil {
return 1
}
if root.Left == nil {
return dfs(root.Right) + 1
}
if root.Right == nil {
return dfs(root.Left) + 1
}
return min(dfs(root.Left), dfs(root.Right)) + 1
} |