codeintuition-logo

Identifying the stateful root to leaf path pattern


The stateful root-to-leaf path technique can only solve a certain type of binary tree problem. These are generally easy or medium problems where we need to find the aggregated value of a function f over all nodes in every root-to-leaf path. For most problems, we need to further aggregate these aggregated values over another function g.

The stateful solution works by maintaining two state variables, one to aggregate the value of nodes in a path over function f and the other to aggregate all root-to-leaf path aggregates over function g. These two variables are either created in the calling function and passed as references to the recursive traversal function or created in the enclosing scope so that all nodes can access the same copy of these two variables.

The stateful solution is the generic solution to all root-to-leaf path problems in a binary tree and can be used to solve all problems that can be solved using the stateless solution. It is used over the stateless version when the values that need to be passed down and up between the nodes are too big

Liking the course? Check our discounted plans to continue learning.