V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Tree Dynamic Programming

Process nodes postorder and combine selected versus unselected child states for maximum independent set.

Core idea

Root the tree and define a small state for each parent-child constraint. For maximum independent set, one state selects the node and forces children out; the other leaves it out and frees each child.

Read the visualization

Rows follow postorder so child states are ready before their parent. The two columns expose the selected and unselected recurrences and their final root comparison.

selectnot selected
root 4
L 1
R 5
LL 3
LR 6

Root the tree and prepare selected and unselected states for every node.

1function rob(root: Node | null): number {
2 const dfs = (nd: Node | null): [number, number] => {
3 if (!nd) return [0, 0]; // empty subtree leaf 0
4 const [ls, ln] = dfs(nd.left); // postorder: compute first child
5 const [rs, rn] = dfs(nd.right);
6 const sel = nd.val + ln + rn; // select sel: child sel not sel select
7 const not = Math.max(ls, ln) + Math.max(rs, rn); // not selected: child not
8 return [sel, not];
9 };
10 return Math.max(...dfs(root)); // root take best maximum
11}
tree ( level order)[4, 1, 5, 3, 6]
postorderLL → LR → L → R → root
1 / 10

Complexity and tradeoffs

Time: O(n). Space: O(n). Each edge contributes once to a constant number of states; recursion depth follows tree height.

Invariant: A completed node row is optimal for its entire subtree under each stated choice for that node.

Where it fits

Tree DP solves independent sets, vertex covers, subtree allocation, and many hierarchical selections. The key is choosing a state that makes child subproblems independent.