Leetcode Note: Go - Maximum Depth of N-ary Tree

Maximum Depth of N-ary Tree - LeetCode
https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

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

所感

  • n-ary tree における深さの最大を求めて int で return する
    • n-ary tree = Generic Tree

回答

Go: Recursive solution - LeetCode Discuss
https://leetcode.com/problems/maximum-depth-of-n-ary-tree/discuss/545916/Go%3A-Recursive-solution

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func maxDepth(root *Node) int {
    if root == nil {
        return 0
    }
    m := 1
    for _, v := range root.Children {
        m = max(m, maxDepth(v)+1)
    }
    return m
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
  • 変数を作成しておき、再帰で更新して return