Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit8285d88

Browse files
Diameter of Binary Tree Java code doesn't work
The code did not work for test case 43, so the submission failed. Probably because of how the static variable and static functions work.I've updated the code to suit the video explanation better, and removed "static" keywords.
1 parent51bcb14 commit8285d88

File tree

1 file changed

+12
-26
lines changed

1 file changed

+12
-26
lines changed
Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,18 @@
11
classSolution {
2-
privatestaticinttreeDiameter =0;
2+
intresult =-1;
33

44
publicintdiameterOfBinaryTree(TreeNoderoot) {
5-
calculateHeight(root);
6-
returntreeDiameter-1;
7-
}
8-
9-
privatestaticintcalculateHeight(TreeNodecurrentNode) {
10-
if (currentNode ==null)
11-
return0;
12-
13-
intleftTreeHeight =calculateHeight(currentNode.left);
14-
intrightTreeHeight =calculateHeight(currentNode.right);
15-
16-
// if the current node doesn't have a left or right subtree, we can't have
17-
// a path passing through it, since we need a leaf node on each side
18-
if (leftTreeHeight !=0 &&rightTreeHeight !=0) {
19-
20-
// diameter at the current node will be equal to the height of left subtree +
21-
// the height of right sub-trees + '1' for the current node
22-
intdiameter =leftTreeHeight +rightTreeHeight +1;
23-
24-
// update the global tree diameter
25-
treeDiameter =Math.max(treeDiameter,diameter);
5+
dfs(root);
6+
returnresult;
267
}
278

28-
// height of the current node will be equal to the maximum of the heights of
29-
// left or right subtrees plus '1' for the current node
30-
returnMath.max(leftTreeHeight,rightTreeHeight) +1;
31-
}
9+
privateintdfs(TreeNodecurrent) {
10+
if (current ==null) {
11+
return -1;
12+
}
13+
intleft =1 +dfs(current.left);
14+
intright =1 +dfs(current.right);
15+
result =Math.max(result, (left +right));
16+
returnMath.max(left,right);
17+
}
3218
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp