-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiameterOfBinaryTree.java
More file actions
43 lines (37 loc) · 1.12 KB
/
diameterOfBinaryTree.java
File metadata and controls
43 lines (37 loc) · 1.12 KB
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
/**
* Author : WindAsMe
* File : diameterOfBinaryTree.java
* Time : Create on 18-9-12
* Location : ../Home/JavaForLeeCode2/diameterOfBinaryTree.java
* Function : LeetCode No.543
*/
public class diameterOfBinaryTree {
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
private static int diameterOfBinaryTreeResult(TreeNode root) {
if (root == null)
return 0;
return Math.max(Math.max(diameterOfBinaryTreeResult(root.left), diameterOfBinaryTreeResult(root.right)), diameter(root));
}
private static int diameter(TreeNode node) {
if (node == null)
return 0;
int sum = 0;
if (node.left != null)
sum += height(node.left);
if (node.right != null)
sum += height(node.right);
return sum;
}
private static int height(TreeNode node) {
if (node == null)
return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
public static void main(String[] args) {
}
}