Leetcode Note: Go - Minimum Depth of Binary Tree

Minimum Depth of Binary Tree - LeetCode
https://leetcode.com/problems/minimum-depth-of-binary-tree/

  • Go 言語で取り組んだメモ

所感

  • 再帰で実装できそう

実装準備

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func minDepth(root *TreeNode) int {
    
}

回答

Golang 4ms recursive - LeetCode Discuss
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/264076/Golang-4ms-recursive

/**
 * 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
	}

	return min(left, right) + 1
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
  • root が nil なら return 0
  • left, right をそれぞれ再帰
  • left か right の depth が 0 なら left + right + 1 を return
  • それ以外なら left か right の小さい方に +1 して return