Maximum Depth of N-Ary Tree

Easy LC problem again but this time the problem doesn’t support Kotlin yet so my solution will be in Java.

class Solution {
    public int maxDepth(Node root) {
        if(root == null) return 0;
        
        int max = 0;
        
        for(Node child : root.children){
            max = Math.max(max, maxDepth(child));
        }
                           
        return max + 1;

    }
}

Recursively traverse all the nodes while keeping track of the highest depth so far.

comments powered by Disqus