-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiameter_of_Binary_Tree.java
More file actions
43 lines (40 loc) · 1.05 KB
/
Diameter_of_Binary_Tree.java
File metadata and controls
43 lines (40 loc) · 1.05 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
import java.util.*;
import java.io.*;
import java.lang.*;
public class 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 {
public int diameterOfBinaryTree(TreeNode root) {
int[] max = new int[1];
fun(root , max);
return max[0];
}
public static int fun(TreeNode root , int[] max)
{
if(root == null)
{
return 0;
}
int l = fun(root.left , max);
int r = fun(root.right , max);
int maxi = l+r;
if(max[0]<maxi)
{
max[0] = maxi;
}
return 1 + Math.max(l , r);
}
}
}