Path Sum

TreeDFS
https://leetcode.com/problems/path-sum

# Definition for a Binary Tree Node

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
1
2
3
4
5

# Solution

Let nn be the number of nodes in the tree.

# DFS

Complexity

time: O(n)O(n)
space: O(n)O(n)

def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:

    def dfs(node: TreeNode, csum: int) -> bool:
        if not node:
            return False
        csum += node.val
        if not node.left and not node.right and csum == targetSum:
            return True
        return dfs(node.left, csum) or dfs(node.right, csum)

    return dfs(root, 0)
1
2
3
4
5
6
7
8
9
10
11