From 6288dbc9830afc15525adfa7e13e11f4008fabcb Mon Sep 17 00:00:00 2001 From: Aniket Mishra <70846580+Aniketmishra0@users.noreply.github.com> Date: Sun, 16 Oct 2022 22:18:51 +0530 Subject: [PATCH] Update binary_tree_path_sum.py --- .../binary_tree/binary_tree_path_sum.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/data_structures/binary_tree/data_structures/binary_tree/binary_tree_path_sum.py b/data_structures/binary_tree/data_structures/binary_tree/binary_tree_path_sum.py index 8b137891791f..e156eac2e207 100644 --- a/data_structures/binary_tree/data_structures/binary_tree/binary_tree_path_sum.py +++ b/data_structures/binary_tree/data_structures/binary_tree/binary_tree_path_sum.py @@ -1 +1,22 @@ + class Solution: + def pathSum(self, root: TreeNode, sum: int) -> int: + global result + result = 0 + + def dfs(node, target): + if node is None: return + find_path_from_node(node, target) + dfs(node.left, target) + dfs(node.right, target) + + def find_path_from_node(node, target): + global result + if node is None: return + if node.val == target: result += 1 + find_path_from_node(node.left, target-node.val) + find_path_from_node(node.right, target-node.val) + + dfs(root, sum) + + return result