-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeDiameter2.java
More file actions
36 lines (31 loc) · 925 Bytes
/
BinaryTreeDiameter2.java
File metadata and controls
36 lines (31 loc) · 925 Bytes
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
27
28
29
30
31
32
33
34
35
36
import java.util.*;
class Program {
// This is an input class. Do not edit.
static class BinaryTree {
public int value;
public BinaryTree left = null;
public BinaryTree right = null;
public BinaryTree(int value) {
this.value = value;
}
}
private static int diameter;
// O(n) time | O(h) space
public int binaryTreeDiameter(BinaryTree tree) {
// Write your code here.
diameter = 0;
helper(tree);
return diameter;
}
private static int helper(BinaryTree root) {
if (root == null) {
return 0;
}
int leftHeight = helper(root.left);
int rightHeight = helper(root.right);
int height = Math.max(leftHeight, rightHeight);
int longestPath = leftHeight + rightHeight;
diameter = Math.max(diameter, longestPath);
return 1 + height;
}
}