Skip to content

Commit 0772a03

Browse files
authored
Update Diameter of N-ary Tree.java
1 parent 1e41ec3 commit 0772a03

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

Medium/Diameter of N-ary Tree.java

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,28 +23,28 @@ public Node(int _val,ArrayList<Node> _children) {
2323

2424
class Solution {
2525
public int diameter(Node root) {
26-
int[] max = {0};
27-
helper(root, max);
28-
return max[0];
26+
int[] diameter = {0};
27+
getHeight(root, diameter);
28+
return diameter[0];
2929
}
3030

31-
private int helper(Node root, int[] max) {
32-
if (root == null) {
31+
private int getHeight(Node node, int[] diameter) {
32+
if (node.children.size() == 0) {
3333
return 0;
3434
}
35-
int max1 = 0;
36-
int max2 = 0;
37-
for (Node child : root.children) {
38-
int height = helper(child, max);
39-
if (max1 < height) {
40-
max2 = max1;
41-
max1 = height;
42-
}
43-
else if (max2 < height) {
44-
max2 = height;
35+
int maxHeightOne = 0;
36+
int maxHeightTwo = 0;
37+
for (Node child : node.children) {
38+
int parentHeight = getHeight(child, diameter) + 1;
39+
if (parentHeight > maxHeightOne) {
40+
maxHeightTwo = maxHeightOne;
41+
maxHeightOne = parentHeight;
42+
} else if (parentHeight > maxHeightTwo) {
43+
maxHeightTwo = parentHeight;
4544
}
45+
int currentDiameter = maxHeightOne + maxHeightTwo;
46+
diameter[0] = Math.max(diameter[0], currentDiameter);
4647
}
47-
max[0] = Math.max(max[0], max1 + max2);
48-
return max1 + 1;
48+
return maxHeightOne;
4949
}
5050
}

0 commit comments

Comments
 (0)