Leetcode - Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree
Leetcode - Word Break

Leetcode - Maximum Depth of N-ary Tree

violet posted @ May 01, 2020 06:12:54 AM in 算法 with tags Algorithm Golang DFS tree , 224 阅读

https://leetcode.com/problems/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).

 

Example 1:

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

 

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

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

func max(a, b int) int {
    if a > b {
        return a
    }
    
    return b
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter