Skip to content

Commit 51bcb14

Browse files
authored
Merge pull request neetcode-gh#113 from ArwaNayef/patch-9
Create 543-Diameter-of-Binary-Tree
2 parents daf2d9e + 08a7b80 commit 51bcb14

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

java/543-Diameter-of-Binary-Tree.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
private static int treeDiameter = 0;
3+
4+
public int diameterOfBinaryTree(TreeNode root) {
5+
calculateHeight(root);
6+
return treeDiameter-1;
7+
}
8+
9+
private static int calculateHeight(TreeNode currentNode) {
10+
if (currentNode == null)
11+
return 0;
12+
13+
int leftTreeHeight = calculateHeight(currentNode.left);
14+
int rightTreeHeight = 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+
int diameter = leftTreeHeight + rightTreeHeight + 1;
23+
24+
// update the global tree diameter
25+
treeDiameter = Math.max(treeDiameter, diameter);
26+
}
27+
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+
return Math.max(leftTreeHeight, rightTreeHeight) + 1;
31+
}
32+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy