The technique involves moving some logic from the caller to the callee. Usually the logic that is moved is a check. Here's an example of the technique applied to code that solves the "Construct BST (Binary Search Tree) from the Preorder Traversal Values" problem leetcode link:
INF = float('inf')
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
def pre(i, lo, hi):
val = preorder[i]
left = right = None
if i+1 < N and lo < preorder[i+1] < val:
left, i = pre(i+1, lo, val)
if i+1 < N and val < preorder[i+1] < hi:
right, i = pre(i+1, val, hi)
node = TreeNode(val, left, right)
return node, i
N = len(preorder)
root, _ = pre(0, -INF, INF)
return root
Then we move the check from the caller to the callee, which simplifies the code somewhat:
INF = float('inf')
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
def pre(i, lo, hi):
if i == N or not lo < preorder[i] < hi:
return None, i-1
val = preorder[i]
left, i = pre(i+1, lo, val)
right, i = pre(i+1, val, hi)
node = TreeNode(val, left, right)
return node, i
N = len(preorder)
root, _ = pre(0, -INF, INF)
return root
Depending on the problem/code and the snippets being moved around, the simplification can be significant.