Skip to content

Commit 8484c4e

Browse files
authored
Create 653_TwoSum_IV-Input_is_a_BST.md
1 parent 5272426 commit 8484c4e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

653_TwoSum_IV-Input_is_a_BST.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
2+
3+
4+
5+
Example 1:
6+
Input: root = [5,3,6,2,4,null,7], k = 9
7+
Output: true
8+
9+
Example 2:
10+
Input: root = [5,3,6,2,4,null,7], k = 28
11+
Output: false
12+
13+
Example 3:
14+
Input: root = [2,1,3], k = 4
15+
Output: true
16+
17+
Example 4:
18+
Input: root = [2,1,3], k = 1
19+
Output: false
20+
21+
Example 5:
22+
Input: root = [2,1,3], k = 3
23+
Output: true
24+
25+
26+
Constraints:
27+
28+
The number of nodes in the tree is in the range [1, 104].
29+
-104 <= Node.val <= 104
30+
root is guaranteed to be a valid binary search tree.
31+
-105 <= k <= 105
32+
33+
34+
```python
35+
def findTarget(self, root: TreeNode, k: int) -> bool:
36+
if root == None: return False
37+
visited = set()
38+
def traverse(cur):
39+
if cur == None: return False
40+
if k-cur.val in visited: return True
41+
visited.add(cur.val)
42+
return traverse(cur.left) or traverse(cur.right)
43+
return traverse(root)
44+
```

0 commit comments

Comments
 (0)