Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

BFS

LC 111. Minimum Depth of Binary Tree

https://leetcode.com/problems/minimum-depth-of-binary-tree/

DFS 解法

/**
 * 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
}
  • No labels