Path Sums

If we want to collect information from the root to any leaf

  • if current node is null, return immediately

  • if current node is a leaf, we know we can return the information along that path from root to this node

  • recursively go to left subtree and append current left node value into our path sum

  • recursively go to right subtree and append current right node value into our path sum

def f(r, s):
            if not r:
                return
            if not r.left and not r.right:   # leaf
                path_sums.append(s)
                return
            if r.left:
                helper(r.left, s + r.left.val)
            if r.right:
                helper(r.right, s + r.right.val)

Last updated