Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Maximum Depth of N-ary Tree

C++, Python and TypeScript solutions for Maximum Depth of N-ary Tree.

The Maximum Depth of N-ary Tree solutions are below.

Solution files

Python•maximum-depth-of-n-ary-tree/synced-solution.py
class Solution:
    def maxDepth(self, root: 'Node') -> int:
        if not root:
            return 0
        if not root.children:
            return 1
        return 1 + max(self.maxDepth(child) for child in root.children)
C++•maximum-depth-of-n-ary-tree/synced-solution.cpp
/* 
// 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;
    }
};
*/
class Solution {
public:
    int maxDepth(Node* root) {
        if (!root) {
            return 0;
        }

        int childDepth = 0;
        for (Node* child : root->children) {
            childDepth = max(childDepth, maxDepth(child));
        }
        return 1 + childDepth;
    }
};
TypeScript•maximum-depth-of-n-ary-tree/synced-solution.ts
function maxDepth(root: _Node | null): number {
    if (!root) {
        return 0;
    }

    let childDepth = 0;
    for (const child of root.children) {
        childDepth = Math.max(childDepth, maxDepth(child));
    }
    return 1 + childDepth;
}