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
class Solution {
 public:
  int diameter(Node* root) {
    int ans = 0;
    maxDepth(root, ans);
    return ans;
  }

 private:
  // Returns the maximum depth of the subtree rooted at `root`.
  int maxDepth(Node* root, int& ans) {
    int maxSubDepth1 = 0;
    int maxSubDepth2 = 0;
    for (Node* child : root->children) {
      const int maxSubDepth = maxDepth(child, ans);
      if (maxSubDepth > maxSubDepth1) {
        maxSubDepth2 = maxSubDepth1;
        maxSubDepth1 = maxSubDepth;
      } else if (maxSubDepth > maxSubDepth2) {
        maxSubDepth2 = maxSubDepth;
      }
    }
    ans = max(ans, maxSubDepth1 + maxSubDepth2);
    return 1 + maxSubDepth1;
  }
};
 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
class Solution {
  public int diameter(Node root) {
    maxDepth(root);
    return ans;
  }

  private int ans = 0;

  // Returns the maximum depth of the subtree rooted at `root`.
  private int maxDepth(Node root) {
    int maxSubDepth1 = 0;
    int maxSubDepth2 = 0;
    for (Node child : root.children) {
      final int maxSubDepth = maxDepth(child);
      if (maxSubDepth > maxSubDepth1) {
        maxSubDepth2 = maxSubDepth1;
        maxSubDepth1 = maxSubDepth;
      } else if (maxSubDepth > maxSubDepth2) {
        maxSubDepth2 = maxSubDepth;
      }
    }
    ans = Math.max(ans, maxSubDepth1 + maxSubDepth2);
    return 1 + maxSubDepth1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def diameter(self, root: 'Node') -> int:
    ans = 0

    def maxDepth(root: 'Node') -> int:
      """Returns the maximum depth of the subtree rooted at `root`."""
      nonlocal ans
      maxSubDepth1 = 0
      maxSubDepth2 = 0
      for child in root.children:
        maxSubDepth = maxDepth(child)
        if maxSubDepth > maxSubDepth1:
          maxSubDepth2 = maxSubDepth1
          maxSubDepth1 = maxSubDepth
        elif maxSubDepth > maxSubDepth2:
          maxSubDepth2 = maxSubDepth
      ans = max(ans, maxSubDepth1 + maxSubDepth2)
      return 1 + maxSubDepth1

    maxDepth(root)
    return ans