Last active
March 31, 2020 12:13
-
-
Save wiccy46/a87805bb07de91d6e16e6632ce97bf6c to your computer and use it in GitHub Desktop.
[binarytree_sum] Binary tree sum #python
This file contains hidden or 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
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