LeetCode 559: Maximum Depth of N-ary Tree

題目:

Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

範例:

Input: root = [1,null,3,2,4,null,5,6]Output: 3

解法:
不管是幾個n-ary tree
就是要找出最大深度
tree的解法通常都是要用遞迴
這次也不例外

在一層遞迴中
要回傳所有子節點的最大深度加上自己這一層的深度

程式碼

/** * Definition for a Node. * type Node struct { *     Val int *     Children []*Node * } */func maxDepth(root *Node) int {    if root == nil {        return 0    }    depth := 1    for _, node := range root.Children {        depth = max(maxDepth(node)+1, depth)    }       return depth}func max(src1 int, src2 int) int {    if (src1 > src2){        return src1    } else {        return src2    }}

沒有留言:

張貼留言

About

努力在程式的大海
用力的揮動雙手
找出屬於自己的航線

Blog Archive

Traffic