You can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def printPaths(root, targetSum):
def dfs(node, currentPath, currentSum):
if not node:
return
currentPath.append(node.val)
currentSum += node.val
if not node.left and not node.right and currentSum == targetSum:
print(currentPath)
dfs(node.left, currentPath, currentSum)
dfs(node.right, currentPath, currentSum)
currentPath.pop()
dfs(root, [], 0)
if __name__ == '__main__':
# Construct binary tree example:
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ \
# 7 2 1
root = TreeNode(5,
TreeNode(4, TreeNode(11, TreeNode(7), TreeNode(2))),
TreeNode(8, TreeNode(13), TreeNode(4, None, TreeNode(1))))
printPaths(root, 22)
You can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.