The total number of nodes is in the range [0, 104].
The depth of the n-ary tree is less than or equal to 1000.
Solutions
Solution 1: Recursion
First, we check if $\textit{root}$ is null. If it is, we return 0. Otherwise, we initialize a variable $\textit{mx}$ to record the maximum depth of the child nodes, then traverse all the child nodes of $\textit{root}$, recursively call the $\text{maxDepth}$ function, and update the value of $\textit{mx}$. Finally, we return $\textit{mx} + 1$.
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes.
1 2 3 4 5 6 7 8 91011121314151617
"""# Definition for a Node.class Node: def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None): self.val = val self.children = children"""classSolution:defmaxDepth(self,root:"Node")->int:ifrootisNone:return0mx=0forchildinroot.children:mx=max(mx,self.maxDepth(child))return1+mx
/*// Definition for a Node.class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; }};*/classSolution{publicintmaxDepth(Noderoot){if(root==null){return0;}intmx=0;for(Nodechild:root.children){mx=Math.max(mx,maxDepth(child));}return1+mx;}}
/*// Definition for a Node.class Node {public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; }};*/classSolution{public:intmaxDepth(Node*root){if(!root){return0;}intmx=0;for(Node*child:root->children){mx=max(mx,maxDepth(child));}returnmx+1;}};
1 2 3 4 5 6 7 8 9101112131415161718
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funcmaxDepth(root*Node)int{ifroot==nil{return0}mx:=0for_,child:=rangeroot.Children{mx=max(mx,maxDepth(child))}return1+mx}