Last active
April 29, 2020 06:17
-
-
Save jonathanagustin/43710fd0e8279206376d62aead48dd3d to your computer and use it in GitHub Desktop.
Branch Sums - algoexpert.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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