Skip to content

Commit 5dbf007

Browse files
committed
Add Solution.java for 0543.Diameter of Binary Tree
1 parent 00cc33a commit 5dbf007

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Invert Binary Tree
2+
3+
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the **longest** path between any two nodes in a tree. This path may or may not pass through the root.
4+
5+
## Example:
6+
```
7+
Given a binary tree:
8+
1
9+
/ \
10+
2 3
11+
/ \
12+
4 5
13+
```
14+
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
15+
16+
## Note:
17+
The length of path between two nodes is represented by the number of edges between them.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
int ans = 1;
12+
13+
public int diameterOfBinaryTree(TreeNode root) {
14+
depth(root);
15+
return ans - 1;
16+
}
17+
18+
public int depth(TreeNode node) {
19+
if (node == null) return 0;
20+
int L = depth(node.left);
21+
int R = depth(node.right);
22+
ans = Math.max(ans, L + R + 1);
23+
return Math.max(L, R) + 1;
24+
}
25+
}

0 commit comments

Comments
 (0)