2Brute2Best
🔥0
03

Subtree answers (bottom-up) (Tree DFS Sub-pattern)

Each node returns a small summary of its subtree, and the global answer is updated while combining the two children.

Signals in the problem statement
  • ›

    "diameter", "longest path between any two nodes"

  • ›

    "height-balanced"

  • ›

    "maximum path sum" where a path may start and end anywhere

  • ›

    "cannot take two directly linked nodes" on a tree

What makes it different

Diameter returns height and updates best = lh + rh. Balanced returns height or −1 as a stop signal, so it stays O(n). House Robber III returns a pair (best if this node is taken, best if skipped), so nothing is recomputed. Maximum Path Sum returns val + max(0, left, right), the best one-sided gain, while the best path bends at some node and uses both sides; start the global at the first node's value, not 0.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Diameter of Binary Tree
    Basic Anchor·LeetCode #543
    Easy
  2. 2
    Balanced Binary Tree
    Basic Reinforcement·LeetCode #110
    Easy
  3. 3
    House Robber III
    Medium·LeetCode #337
    Medium
  4. 4
    Binary Tree Maximum Path Sum
    Interview-Level·LeetCode #124
    Hard

Template

subtree-answer-template.cpp
// Bottom-up: each call returns a summary of its subtree; the global answer is
// updated while combining the two children. Here: diameter (longest path, in edges).
int best = 0;

int height(TreeNode* node) {                             // returns: nodes on the longest downward path
    if (!node) return 0;
    int lh = height(node->left);
    int rh = height(node->right);
    best = max(best, lh + rh);                           // the longest path that bends at this node
    return 1 + max(lh, rh);                              // a parent can only extend ONE side
}

int diameterOfBinaryTree(TreeNode* root) {
    best = 0;
    height(root);
    return best;
}
Remember this · Tree DFS
Trigger
Paths, heights, diameters, validating structure, ancestors, anything "for every subtree".
Think
If my left and right children already gave me their answers, how do I build mine?
Key question
What does my recursive function return, and what do I pass down?