Find Largest subtree sum in a tree

Pattern: Tree DP basics

medium

Compute every subtree's sum bottom up: a node's subtree sum is its value plus both children's sums. Track the largest one seen.

The problem

Return the largest sum of all values in a subtree (a node and everything below it). [1, -2, 3, 4, 5, -6, 2] gives 7. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • How is a subtree's sum built from smaller ones?
  • In what order must nodes be processed?
  • What should the best start at?

Hints

    Brute force, and why it fails

    Sum every subtree separately: O(n²).

    The key insight

    Each subtree sum reuses its children's, so one post-order pass computes all of them.

    Dry run

    best5

    Tree [1, -2, 3, 4, 5, -6, 2]. Subtree sums of the leaves: 4, 5, -6, 2.

    Step 1 of 3

    The plan

    total(n): if null: 0
              s = n.val + total(left) + total(right)
              best = max(best, s); return s
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    One pass.

    Edge cases

    • All negative: the largest single value.
    • One node.
    • The whole tree is best.
    I've built my logic, show the code

    Java

    class Solution {
        private int best;
    
        public int findLargestSubtreeSum(TreeNode root) {
            best = Integer.MIN_VALUE;
            total(root);
            return best;
        }
    
        private int total(TreeNode n) {             // post-order: children first
            if (n == null) return 0;
            int s = n.val + total(n.left) + total(n.right);
            best = Math.max(best, s);               // every subtree is checked once
            return s;
        }
    }

    C++

    class Solution {
    public:
        int best;
    
        int findLargestSubtreeSum(TreeNode* root) {
            best = INT_MIN;
            total(root);
            return best;
        }
    
        int total(TreeNode* n) {                    // post-order: children first
            if (n == NULL) return 0;
            int s = n->val + total(n->left) + total(n->right);
            best = max(best, s);                    // every subtree is checked once
            return s;
        }
    };

    Python

    class Solution:
        def findLargestSubtreeSum(self, root) -> int:
            best = float("-inf")
    
            def total(n) -> int:                    # post-order: children first
                nonlocal best
                if n is None:
                    return 0
                s = n.val + total(n.left) + total(n.right)
                best = max(best, s)                 # every subtree is checked once
                return s
    
            total(root)
            return best

    Common mistakes

    • Starting best at 0.
    • Ignoring subtrees that are not the whole tree.

    Similar problems