Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Update 543-Diameter-of-Binary-Tree.java
The solution is not working.

1. treeDiameter should be cleared. leetcode runs multiple tests & the static value is persisted. (or better don't use static variable)
2. single node TreeNode(1, null,null) should return 0
3. diameter should be calculated when at least one leaf != 0
  • Loading branch information
predam authored Apr 11, 2022
commit 4121cd5bce98144f6c25ae52bbdb17e6f63da16c
15 changes: 8 additions & 7 deletions java/543-Diameter-of-Binary-Tree.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
class Solution {
private static int treeDiameter = 0;

private static int treeDiameter = 0;

public int diameterOfBinaryTree(TreeNode root) {
calculateHeight(root);
return treeDiameter-1;
public int diameterOfBinaryTree(TreeNode root) {
calculateHeight(root);
int result = treeDiameter-1;
treeDiameter = 0;
return Math.max(0, result);
}

private static int calculateHeight(TreeNode currentNode) {
Expand All @@ -13,9 +16,7 @@ private static int calculateHeight(TreeNode currentNode) {
int leftTreeHeight = calculateHeight(currentNode.left);
int rightTreeHeight = calculateHeight(currentNode.right);

// if the current node doesn't have a left or right subtree, we can't have
// a path passing through it, since we need a leaf node on each side
if (leftTreeHeight != 0 && rightTreeHeight != 0) {
if (leftTreeHeight != 0 || rightTreeHeight != 0) {

// diameter at the current node will be equal to the height of left subtree +
// the height of right sub-trees + '1' for the current node
Expand Down