Print All Paths in a Binary Tree with a Given Sum - Code Examples
⬅ Previous TopicCalculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
Next Topic ⮕Find the Distance Between Two Nodes in a Binary Tree
Next Topic ⮕Find the Distance Between Two Nodes in a Binary Tree
Solution
Algorithm Steps
Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
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)