The maximum depth of an N-ary tree is the longest path from the root to any leaf. We can recursively compute the depth for each child and take the maximum.
classSolution {
public:int maxDepth(Node* root) {
if (!root) return0;
int ans =0;
for (auto c : root->children) {
ans = max(ans, maxDepth(c));
}
return ans +1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
typeNodestruct {
ValintChildren []*Node}
funcmaxDepth(root*Node) int {
ifroot==nil {
return0 }
ans:=0for_, c:=rangeroot.Children {
d:=maxDepth(c)
ifd > ans {
ans = d }
}
returnans+1}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintmaxDepth(Node root) {
if (root ==null) return 0;
int ans = 0;
for (Node c : root.children) {
ans = Math.max(ans, maxDepth(c));
}
return ans + 1;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funmaxDepth(root: Node?): Int {
if (root ==null) return0var ans = 0for (c in root.children) {
ans = maxOf(ans, maxDepth(c))
}
return ans + 1 }
}
1
2
3
4
5
6
7
8
classSolution:
defmaxDepth(self, root: 'Node') -> int:
ifnot root:
return0 ans =0for c in root.children:
ans = max(ans, self.maxDepth(c))
return ans +1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmax_depth(root: Option<Rc<RefCell<Node>>>) -> i32 {
fndfs(node: Option<Rc<RefCell<Node>>>) -> i32 {
iflet Some(n) = node {
let n = n.borrow();
letmut ans =0;
for c in&n.children {
ans = ans.max(dfs(c.clone()));
}
ans +1 } else {
0 }
}
dfs(root)
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
maxDepth(root: Node|null):number {
if (!root) return0;
letans=0;
for (constcofroot.children) {
ans= Math.max(ans, this.maxDepth(c));
}
returnans+1;
}
}