Identifying the simultaneous traversal pattern


The simultaneous traversal technique can only solve certain types of binary tree problems. These are generally easy or medium problems where we are given two binary trees and a function f, and we need to apply the function f over all the corresponding nodes in the two trees. The function f may also update the structure of the tree. Some problems may require further aggregating these values of another function g. The problem defines the definition of what constitutes corresponding nodes. Generally, two nodes in two trees are said to be corresponding nodes when they overlap if the trees are placed on top of each other.

If the problem statement or its solution follows the generic template below, it can be solved by applying the simultaneous traversal technique.

Template:

Given two binary trees, apply the function f on the corresponding nodes in the trees and aggregate the values over a function g.

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