15 Jun 2024C++ / Python / TypeScriptEasy

Maximum Depth of N-ary Tree

Collected C++, Python, TypeScript solutions for maximum depth of n-ary tree. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Maximum Depth of N-ary Tree. the solution files are available below.

solution files

  • C++ maximum-depth-of-n-ary-tree/synced-solution.cpp
  • Python maximum-depth-of-n-ary-tree/synced-solution.py
  • TypeScript maximum-depth-of-n-ary-tree/synced-solution.ts

Solution files

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

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

    let childDepth = class="syntax-number">0;
    for (const child of root.children) {
        childDepth = Math.max(childDepth, maxDepth(child));
    }
    return class="syntax-number">1 + childDepth;
}