Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trees

Maximum Sum BST in a Binary Tree

Hard · Trees · Asked at Amazon, Google, Microsoft

Find the subtree (a node with all of its descendants) that is a valid binary search tree — every value in a left subtree is strictly smaller than its node and every value in a right subtree is strictly larger — and has the largest sum of values. Print that sum. An empty tree counts as a BST with sum 0, so the answer is never negative.

Input

First line: k. Second line: k values — the tree in level order, -1 means no node.

Output

The maximum sum of a BST subtree.

Constraints

Post-order DFS returning, for each subtree: is it a BST, its minimum, its maximum and its sum. A node forms a BST when both children do and left max < node < right min. Track the best sum over all BST subtrees.

Example 1

Input

15
1 4 3 2 4 2 5 -1 -1 -1 -1 -1 -1 4 6

Output

20

Example 2

Input

3
-4 -2 -5

Output

0

Hints

  1. Whether a subtree is a BST depends only on its children’s answers.
  2. Return four things from each subtree: is it a BST, its minimum, its maximum, its sum.
  3. A node closes a BST when both children are BSTs and left max < node < right min.

Approach

Process nodes in post-order (children before parents — reversing a preorder that pushes left then right gives this without recursion). An empty child counts as a BST with min = +∞ and max = −∞, so the checks work at leaves. When a node forms a BST, its sum is left sum + right sum + value; update the best. Start the best at 0 for the empty BST, so all-negative trees print 0.

Complexity: O(n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

struct Node {
    long long val;
    Node *left = nullptr, *right = nullptr;
    Node(long long v) : val(v) {}
};

// level order with -1 for a missing child
Node *build(const vector<long long> &a) {
    if (a.empty() || a[0] == -1) return nullptr;
    Node *root = new Node(a[0]);
    queue<Node *> q;
    q.push(root);
    size_t i = 1;
    while (!q.empty() && i < a.size()) {
        Node *cur = q.front();
        q.pop();
        if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
        i++;
        if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
        i++;
    }
    return root;
}

vector<long long> readTree() {
    int k;
    cin >> k;
    vector<long long> a(k);
    for (auto &x : a) cin >> x;
    return a;
}

struct Info {
    bool bst;
    long long mn, mx, sum;
};

int main() {
    Node *root = build(readTree());
    vector<Node *> order, st = {root};
    while (!st.empty()) {
        Node *n = st.back();
        st.pop_back();
        order.push_back(n);
        if (n->left) st.push_back(n->left);
        if (n->right) st.push_back(n->right);
    }
    unordered_map<Node *, Info> info;
    Info empty{true, LLONG_MAX, LLONG_MIN, 0};
    long long best = 0;
    for (int i = (int) order.size() - 1; i >= 0; i--) {
        Node *n = order[i];
        Info L = n->left ? info[n->left] : empty, R = n->right ? info[n->right] : empty;
        if (L.bst && R.bst && L.mx < n->val && n->val < R.mn) {
            long long sum = L.sum + R.sum + n->val;
            best = max(best, sum);
            info[n] = {true, min(L.mn, n->val), max(R.mx, n->val), sum};
        } else info[n] = {false, 0, 0, 0};
    }
    cout << best << "\n";
    return 0;
}

Python solution

import sys
from collections import deque

class Node:
    __slots__ = ("val", "left", "right")

    def __init__(self, val):
        self.val, self.left, self.right = val, None, None


def build(a):
    """Level order with -1 for a missing child."""
    if not a or a[0] == -1:
        return None
    root = Node(a[0])
    q = deque([root])
    i = 1
    while q and i < len(a):
        cur = q.popleft()
        if i < len(a) and a[i] != -1:
            cur.left = Node(a[i])
            q.append(cur.left)
        i += 1
        if i < len(a) and a[i] != -1:
            cur.right = Node(a[i])
            q.append(cur.right)
        i += 1
    return root


data = list(map(int, sys.stdin.read().split()))
root = build(data[1 : 1 + data[0]])
order, stack = [], [root]
while stack:
    node = stack.pop()
    order.append(node)
    if node.left:
        stack.append(node.left)
    if node.right:
        stack.append(node.right)
INF = float("inf")
EMPTY = (True, INF, -INF, 0)
info = {}
best = 0
for node in reversed(order):
    L = info[id(node.left)] if node.left else EMPTY
    R = info[id(node.right)] if node.right else EMPTY
    if L[0] and R[0] and L[2] < node.val < R[1]:
        s = L[3] + R[3] + node.val
        best = max(best, s)
        info[id(node)] = (True, min(L[1], node.val), max(R[2], node.val), s)
    else:
        info[id(node)] = (False, 0, 0, 0)
print(best)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    static class Node {
        long val;
        Node left, right;
        Node(long v) { val = v; }
    }

    // level order with -1 for a missing child
    static Node build(long[] a) {
        if (a.length == 0 || a[0] == -1) return null;
        Node root = new Node(a[0]);
        ArrayDeque<Node> q = new ArrayDeque<>();
        q.add(root);
        int i = 1;
        while (!q.isEmpty() && i < a.length) {
            Node cur = q.poll();
            if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
            i++;
            if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
            i++;
        }
        return root;
    }

    static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    static long next() throws IOException {
        in.nextToken();
        return (long) in.nval;
    }

    static long[] readTree() throws IOException {
        int k = (int) next();
        long[] a = new long[k];
        for (int i = 0; i < k; i++) a[i] = next();
        return a;
    }

    public static void main(String[] args) throws IOException {
        Node root = build(readTree());
        ArrayList<Node> order = new ArrayList<>();
        ArrayDeque<Node> st = new ArrayDeque<>();
        st.push(root);
        while (!st.isEmpty()) {
            Node n = st.pop();
            order.add(n);
            if (n.left != null) st.push(n.left);
            if (n.right != null) st.push(n.right);
        }
        // info per node: {isBst (1/0), min, max, sum}
        HashMap<Node, long[]> info = new HashMap<>();
        long[] empty = {1, Long.MAX_VALUE, Long.MIN_VALUE, 0};
        long best = 0;
        for (int i = order.size() - 1; i >= 0; i--) {
            Node n = order.get(i);
            long[] L = n.left != null ? info.get(n.left) : empty;
            long[] R = n.right != null ? info.get(n.right) : empty;
            if (L[0] == 1 && R[0] == 1 && L[2] < n.val && n.val < R[1]) {
                long sum = L[3] + R[3] + n.val;
                best = Math.max(best, sum);
                info.put(n, new long[] {1, Math.min(L[1], n.val), Math.max(R[2], n.val), sum});
            } else info.put(n, new long[] {0, 0, 0, 0});
        }
        System.out.println(best);
    }
}

Solve Maximum Sum BST in a Binary Tree online · All practice problems