Skip to content

1522. Diameter of N-Ary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  int diameter(Node* root) {
    int ans = 0;
    maxDepth(root, ans);
    return ans;
  }

 private:
  int maxDepth(Node* root, int& ans) {
    int max1 = 0;
    int max2 = 0;

    for (Node* child : root->children) {
      const int depth = maxDepth(child, ans);
      if (depth > max1) {
        max2 = max1;
        max1 = depth;
      } else if (depth > max2) {
        max2 = depth;
      }
    }

    ans = max(ans, max1 + max2);
    return 1 + max1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public int diameter(Node root) {
    maxDepth(root);
    return ans;
  }

  private int ans = 0;

  private int maxDepth(Node root) {
    int max1 = 0;
    int max2 = 0;

    for (Node child : root.children) {
      final int depth = maxDepth(child);
      if (depth > max1) {
        max2 = max1;
        max1 = depth;
      } else if (depth > max2) {
        max2 = depth;
      }
    }

    ans = Math.max(ans, max1 + max2);
    return 1 + max1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
  def diameter(self, root: 'Node') -> int:
    ans = 0

    def maxDepth(root: 'Node') -> int:
      nonlocal ans
      max1 = 0
      max2 = 0

      for child in root.children:
        depth = maxDepth(child)
        if depth > max1:
          max2 = max1
          max1 = depth
        elif depth > max2:
          max2 = depth

      ans = max(ans, max1 + max2)
      return 1 + max1

    maxDepth(root)
    return ans