-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLargestTreeSumPath.java
121 lines (101 loc) · 2.65 KB
/
LargestTreeSumPath.java
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*https://binarysearch.com/problems/Largest-Tree-Sum-Path*/
import java.util.*;
/**
* public class Tree {
* int val;
* Tree left;
* Tree right;
* }
*/
class Solution {
int max = 0;
public int solve(Tree root) {
max = 0;
recur(root);
return max;
}
public int recur(Tree root)
{
if (root == null) return 0;
int left = recur(root.left);
int right = recur(root.right);
if (root.val > max) max = root.val;
if (root.val+left > max) max = left+root.val;
if (root.val+right > max) max = right+root.val;
if (left+right+root.val > max) max = left+right+root.val;
if (root.left == null && root.right == null) return root.val;
return Math.max(left+root.val,Math.max(root.val,right+root.val));
}
}
import java.util.*;
/**
* public class Tree {
* int val;
* Tree left;
* Tree right;
* }
*/
class Solution {
int max = 0;
public int solve(Tree root) {
max = 0;
recur(root);
return max;
}
public int recur(Tree root)
{
if (root == null) return 0;
int left = recur(root.left);
int right = recur(root.right);
max = findMax(max,root.val,root.val+left,root.val+right,root.val+left+right);
if (root.left == null && root.right == null) return root.val;
return findMax(root.val,left+root.val,right+root.val);
}
public int findMax(int... nums)
{
int maxNum = Integer.MIN_VALUE;
for (int i : nums)
if (i > maxNum)
maxNum = i;
return maxNum;
}
}
//single function solution
import java.util.*;
/**
* public class Tree {
* int val;
* Tree left;
* Tree right;
* }
*/
class Solution {
int max = -1;
public int solve(Tree root) {
//trick to distinguish between tree root and other nodes
boolean flag = false;
if (max == -1)
{
max = Integer.MIN_VALUE;
flag = true;
}
//solution
if (root == null) return 0;
int left = solve(root.left);
int right = solve(root.right);
max = findMax(max,root.val,root.val+left,root.val+right,root.val+left+right);
//trick to distinguish between tree root and other nodes
if (flag) return max;
//solution
if (root.left == null && root.right == null) return root.val;
return findMax(root.val,left+root.val,right+root.val);
}
public int findMax(int... nums)
{
int maxNum = Integer.MIN_VALUE;
for (int i : nums)
if (i > maxNum)
maxNum = i;
return maxNum;
}
}