Skip to content

Commit a84f7ba

Browse files
committed
BST - easy - check if bst has two nodes sum equal to target
1 parent f363fdf commit a84f7ba

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

binary_search_tree/easy/two_sum_iv.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Definition for a binary tree node.
2+
from typing import Optional
3+
4+
5+
class TreeNode:
6+
def __init__(self, val=0, left=None, right=None):
7+
self.val = val
8+
self.left = left
9+
self.right = right
10+
11+
12+
class Solution:
13+
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
14+
15+
result = []
16+
17+
def dfs(node):
18+
if node:
19+
dfs(node.left)
20+
result.append(node.val)
21+
dfs(node.right)
22+
23+
dfs(root)
24+
25+
p1 = 0
26+
p2 = len(result) - 1
27+
while p1 < p2:
28+
s = result[p1] + result[p2]
29+
if s == k:
30+
return True
31+
elif s < k:
32+
p1 += 1
33+
else:
34+
p2 -= 1
35+
return False

0 commit comments

Comments
 (0)