Skip to content

Commit 0ea3965

Browse files
committed
LC#543, 2nd approach, diameter of binary tree
1 parent c2ca366 commit 0ea3965

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

β€ŽLeetcode/easy/DiameterOfBinaryTree543.javaβ€Ž

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ public class TreeNode {
2222

2323
int ans = 0;
2424

25-
public int diameterOfBinaryTree(TreeNode root) {
25+
public int diameterOfBinaryTree1(TreeNode root) {
2626
if (root == null)
2727
return 0;
2828

@@ -33,8 +33,8 @@ public int diameterOfBinaryTree(TreeNode root) {
3333
if (diameter > ans)
3434
ans = diameter;
3535

36-
diameterOfBinaryTree(root.left);
37-
diameterOfBinaryTree(root.right);
36+
diameterOfBinaryTree1(root.left);
37+
diameterOfBinaryTree1(root.right);
3838

3939
return ans;
4040
}
@@ -51,4 +51,31 @@ private int height(TreeNode node) {
5151

5252
return Math.max(lheight, rheight);
5353
}
54+
55+
private int height1(TreeNode node) {
56+
if (node == null)
57+
return -1;
58+
59+
int lheight = height1(node.left);
60+
int rheight = height1(node.right);
61+
62+
return Math.max(lheight, rheight) + 1;
63+
}
64+
65+
public int diameterOfBinaryTree(TreeNode root) {
66+
if (root == null)
67+
return 0;
68+
// max distance between two nodes of LHS
69+
int leftDia = diameterOfBinaryTree(root.left);
70+
// max distance between two nodes of RHS
71+
int rightDia = diameterOfBinaryTree(root.right);
72+
73+
// diameter that passes through the root node
74+
int rootWayDia = height1(root.left) + height1(root.right) + 2;
75+
76+
int dia = Math.max(rootWayDia, Math.max(leftDia, rightDia));
77+
78+
return dia;
79+
}
80+
5481
}

0 commit comments

Comments
Β (0)