-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiameter of Binary Tree.java
51 lines (42 loc) · 1.38 KB
/
Diameter of Binary Tree.java
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// https://leetcode.com/problems/diameter-of-binary-tree/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int maxDiameter;
private int dfs(TreeNode root) {
// A tree with no children has a height of 0
if (root == null) {
return 0;
}
// Calculate maximum height of subtrees
int maxLeftHeight = dfs(root.left);
int maxRightHeight = dfs(root.right);
// Update maxDiameter by merging height of both subtrees
maxDiameter = Math.max(maxDiameter, maxLeftHeight + maxRightHeight);
// (Because this is a dfs algorithm) Return maximum subtree height and add 1 for current root
return Math.max(maxLeftHeight, maxRightHeight) + 1;
}
public int diameterOfBinaryTree(TreeNode root) {
/*
* Time Complexity: O(n) where n = number of nodes inside tree
*
* Space Complexity: O(n) where n = number of nodes inside tree. dfs() is called for every node.
*/
maxDiameter = 0;
dfs(root);
return maxDiameter;
}
}