Skip to content

Instantly share code, notes, and snippets.

@jacygao
Created November 8, 2020 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacygao/9f2711cd62cb0a5326cbd2c59b350e1b to your computer and use it in GitHub Desktop.
Save jacygao/9f2711cd62cb0a5326cbd2c59b350e1b to your computer and use it in GitHub Desktop.
Given a n-ary tree, find its maximum depth.
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
return dfs(root);
}
public int dfs(Node n) {
int maxChild = 0;
for (Node child : n.children) {
int childDep = dfs(child);
if (childDep > maxChild) {
maxChild = childDep;
}
}
maxChild++;
return maxChild;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment