Overview
Tree DP is just DP where the "graph" of states is a tree. Since trees don't have cycles, we don't need a `visited` array, just a `parent` pointer to avoid going backward.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Learn how to aggregate data efficiently across a tree structure using Depth-First Search (DFS) and post-order traversal.
Tree DP is just DP where the "graph" of states is a tree. Since trees don't have cycles, we don't need a `visited` array, just a `parent` pointer to avoid going backward.
Most Tree DP problems use Post-Order Traversal. You visit the children, get their answers, and then use those answers to compute the parent's answer.
Usually, `dp[u]` represents the answer for the subtree rooted at node `u`. For example, `dp[u]` could be the maximum path sum in that subtree.
Often, the function returns a local answer to help the parent, but updates a global variable (like `max_path`) during the process, since the best path might not go through the ultimate root.