Skip to content

Instantly share code, notes, and snippets.

@wiccy46
Last active March 31, 2020 12:13
Show Gist options
  • Save wiccy46/a87805bb07de91d6e16e6632ce97bf6c to your computer and use it in GitHub Desktop.
Save wiccy46/a87805bb07de91d6e16e6632ce97bf6c to your computer and use it in GitHub Desktop.
[binarytree_sum] Binary tree sum #python
def search_path(root):
if root is None:
return []
if root.left is None and root.right is None:
return [root.value]
return [root.value + val for val in search_path(root.right)
+ search_path(root.left)]
# or
def calcSum(node, runningSum, sums):
if node is None:
return
newRunningSum = runningSum + node.value
if node.left is None and node.right is None: #leaf node
sums.append(newRunningSum)
return
calcSum(node.left, newRunningSum, sums)
calcSum(node.right, newRunningSum, sums)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment