Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 081651f

Browse files
committed
Added Maximum Sum BST in Binary Tree.java
1 parent 581d814 commit 081651f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public int maxSumBST(TreeNode root) {
18+
int[] ans = {0};
19+
helper(root, ans);
20+
return ans[0];
21+
}
22+
23+
private int[] helper(TreeNode root, int[] ans) {
24+
if (root == null) {
25+
// new int[]{min, max, sum}
26+
return new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
27+
}
28+
int[] left = helper(root.left, ans);
29+
int[] right = helper(root.right, ans);
30+
if (!(left != null && right != null && root.val > left[1] && root.val < right[0])) {
31+
return null;
32+
}
33+
int sum = root.val + left[2] + right[2];
34+
ans[0] = Math.max(ans[0], sum);
35+
int min = Math.min(root.val, left[0]);
36+
int max = Math.max(root.val, right[1]);
37+
return new int[]{min, max, sum};
38+
}
39+
}

0 commit comments

Comments
 (0)