Skip to content

Instantly share code, notes, and snippets.

@jonathanagustin
Last active April 29, 2020 06:17
Show Gist options
  • Save jonathanagustin/43710fd0e8279206376d62aead48dd3d to your computer and use it in GitHub Desktop.
Save jonathanagustin/43710fd0e8279206376d62aead48dd3d to your computer and use it in GitHub Desktop.
Branch Sums - algoexpert.io
"""
https://www.algoexpert.io/questions/Branch%20Sums
"""
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
"""
O(n) time | O(n) space
n = number of nodes in BinaryTree
"""
def branchSums(root):
sums = []
recurseBranchSums(root, 0, sums)
return sums
def recurseBranchSums(node, currentSum, sums):
if node is None:
return
currentSum += node.value
if node.left is None and node.right is None:
sums.append(currentSum)
return
recurseBranchSums(node.left, currentSum, sums)
recurseBranchSums(node.right, currentSum, sums)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment