Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 1448 Count Good Nodes in Binary Tree - Implementation

Top-down DFS pattern

dfs(node,pathMax)dfs(node, pathMax): returns count of good nodes in subtree. Add 1 if node.valpathMaxnode.val \geq pathMax. Recurse on children with newMax=max(pathMax,node.val)newMax = \max(pathMax, node.val). Sum the results. Base case: null returns 00. Leaf returns 11 if good, 00 otherwise. Time: O(n)O(n), Space: O(h)O(h). This is the template for top-down tree DP: carry state down, aggregate results up. This is one of the simpler tree DP problems. It demonstrates the top-down pattern clearly.

Time complexity: O(n)O(n).

Space complexity: O(h)O(h).