forked from prateekshyap/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubtreeWithMaximumValue.java
64 lines (58 loc) · 1.26 KB
/
SubtreeWithMaximumValue.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
/*https://binarysearch.com/problems/Subtree-with-Maximum-Value*/
import java.util.*;
/**
* public class Tree {
* int val;
* Tree left;
* Tree right;
* }
*/
class Solution {
int max;
public int solve(Tree root) {
max = 0;
recur(root);
return max;
}
public int recur(Tree root)
{
if (root == null) return 0;
if (root.left == null && root.right == null)
{
if (root.val > max) max = root.val;
return root.val;
}
int sum = recur(root.left)+recur(root.right)+root.val;
if (sum > max) max = sum;
return sum;
}
}
import java.util.*;
/**
* public class Tree {
* int val;
* Tree left;
* Tree right;
* }
*/
class Solution {
int max = -1;
public int solve(Tree root) {
boolean changed = false;
if (max == -1)
{
changed = true;
max = 0;
}
if (root == null) return 0;
if (root.left == null && root.right == null)
{
if (root.val > max) max = root.val;
return root.val;
}
int sum = solve(root.left)+solve(root.right)+root.val;
if (sum > max) max = sum;
if (changed) return max;
return sum;
}
}