File tree Expand file tree Collapse file tree 2 files changed +8
-8
lines changed Expand file tree Collapse file tree 2 files changed +8
-8
lines changed Original file line number Diff line number Diff line change 1616<pre >
1717<strong >Input:</strong > root = [1,2,3], targetSum = 5
1818<strong >Output:</strong > false
19- <strong >Explanation:</strong > There two root-to-leaf paths in the tree:
19+ <strong >Explanation:</strong > There are two root-to-leaf paths in the tree:
2020(1 --> ; 2): The sum is 3.
2121(1 --> ; 3): The sum is 4.
2222There is no root-to-leaf path with sum = 5.
Original file line number Diff line number Diff line change 1- # Approach 1 - Recursion
1+ # Approach 1: Recursion
22
3- # Time: O(N )
4- # Space: O(N ) in worst case , O(log N ) in best case
3+ # Time: O(n )
4+ # Space: O(n ) in worst base , O(log n ) in best case
55
66# Definition for a binary tree node.
77# class TreeNode:
88# def __init__(self, val=0, left=None, right=None):
99# self.val = val
1010# self.left = left
1111# self.right = right
12-
1312class Solution :
1413 def hasPathSum (self , root : Optional [TreeNode ], targetSum : int ) -> bool :
1514 if not root :
1615 return False
17-
16+
1817 targetSum -= root .val
19- if not root .left and not root .right :
18+
19+ if not root .left and not root .right : # reached leaf
2020 return targetSum == 0
21-
21+
2222 return self .hasPathSum (root .left , targetSum ) or self .hasPathSum (root .right , targetSum )
2323
You can’t perform that action at this time.
0 commit comments