-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeMaxPathSum.java
More file actions
80 lines (77 loc) · 2.04 KB
/
TreeMaxPathSum.java
File metadata and controls
80 lines (77 loc) · 2.04 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*package whatever //do not write package name here */
import java.io.*;
class Node
{
int data;
Node left,right;
public Node(int data)
{
this.data = data;
left=right=null;
}
}
class Temp
{
int value;
}
class GFG {
public static void inOrder(Node root)
{
if(root==null) return;
inOrder(root.left);
System.out.print(root.data+" ");
inOrder(root.right);
}
public static Node createTree(int[] arr,Node root,int i)
{
if(i<arr.length)
{
Node temp = new Node(arr[i]);
root = temp;
root.left = createTree(arr,root.left,(2*i)+1);
root.right = createTree(arr,root.right,(2*i)+2);
}
return root;
}
public static int getDiameter(Node root)
{
Temp tmp = new Temp();
tmp.value = Integer.MIN_VALUE;
maxPathUtil(tmp,root);
return tmp.value;
}
public static int maxPathUtil(Temp t, Node root)
{
if(root==null)
return 0;
if(root.left==null && root.right==null)
return root.data;
int ls = maxPathUtil(t,root.left);
int rs = maxPathUtil(t,root.right);
if(root.left!=null && root.right!=null)
{
t.value = Math.max(t.value,ls+rs+root.data);
return Math.max(ls,rs) + root.data;
}
return (root.left==null)? rs+root.data : ls+root.data;
}
public static int height(Node root)
{
if(root==null)return 0;
return 1 + Math.max(height(root.left),height(root.right));
}
public static int printMaxDiameterPath(int[] arr,int nodes)
{
//we will create a tree here using a dummy node.
Node a = new Node(0);
Node root = createTree(arr,a,0);
// inOrder(root);
int maxsum = getDiameter(root);
return maxsum;
}
public static void main (String[] args) {
int[] arr = {2,4,5,8,-4,3,-6};
int nodes = 7;
System.out.println(printMaxDiameterPath(arr,nodes));
}
}