← Bytedance Interview Insights
I knew this was a tree DP problem pretty quickly but fumbled the state definition at first.
Use dynamic programming on the tree, where for each node you compute two values: the maximum sum when the node is included and when it is excluded. Then combine these values bottom-up to get the global maximum.
Pro tip: Clarify that the tree is binary and values are non-negative, which simplifies the DP because excluding a node never forces inclusion of its children. Also, mention that the solution runs in O(n) time and O(h) space for recursion, which is optimal.
For each node, define two states: include (max sum if this node is selected) and exclude (max sum if this node is not selected).
For a null node, both include and exclude sums are 0.
If a node is included, its children must be excluded: include = node.val + left.exclude + right.exclude. If excluded, children can be either included or excluded: exclude = max(left.include, left.exclude) + max(right.include, right.exclude).
Compute the DP values for each node via a post-order traversal, returning both values from each recursive call.
At the root, the maximum sum is max(root.include, root.exclude).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.