2
2
3
3
import com .fishercoder .common .classes .TreeNode ;
4
4
5
- /**
6
- * 1373. Maximum Sum BST in Binary Tree
7
- *
8
- * Given a binary tree root, the task is to return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).
9
- * Assume a BST is defined as follows:
10
- * The left subtree of a node contains only nodes with keys less than the node's key.
11
- * The right subtree of a node contains only nodes with keys greater than the node's key.
12
- * Both the left and right subtrees must also be binary search trees.
13
- *
14
- * Example 1:
15
- * Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
16
- * Output: 20
17
- * Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.
18
- *
19
- * Example 2:
20
- * Input: root = [4,3,null,1,2]
21
- * Output: 2
22
- * Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.
23
- *
24
- * Example 3:
25
- * Input: root = [-4,-2,-5]
26
- * Output: 0
27
- * Explanation: All values are negatives. Return an empty BST.
28
- *
29
- * Example 4:
30
- * Input: root = [2,1,3]
31
- * Output: 6
32
- *
33
- * Example 5:
34
- * Input: root = [5,4,8,3,null,6,3]
35
- * Output: 7
36
- *
37
- * Constraints:
38
- * Each tree has at most 40000 nodes..
39
- * Each node's value is between [-4 * 10^4 , 4 * 10^4].
40
- * */
41
5
public class _1373 {
42
6
public static class Solution1 {
43
7
/**
44
8
* credit: https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/532021/Java-Post-Order
45
- * * /
9
+ */
46
10
public int maxSumBST (TreeNode root ) {
47
11
return postOrder (root )[4 ];
48
12
}
@@ -53,7 +17,7 @@ public int maxSumBST(TreeNode root) {
53
17
* result[2] means the left boundary
54
18
* result[3] means the right boundary
55
19
* result[4] means the global max sum
56
- * * /
20
+ */
57
21
private int [] postOrder (TreeNode root ) {
58
22
if (root == null ) {
59
23
return new int []{1 , 0 , Integer .MAX_VALUE , Integer .MIN_VALUE , 0 };
0 commit comments