Skip to content

Commit eebb96f

Browse files
authored
Create 653._Two_Sum_IV_-_Input_is_a_BST.md
1 parent e50abed commit eebb96f

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# 653. Two Sum IV - Input is a BST
2+
3+
**<font color=red>难度: Easy</font>**
4+
5+
## 刷题内容
6+
7+
> 原题连接
8+
9+
* https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/
10+
11+
> 内容描述
12+
13+
```
14+
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
15+
16+
Example 1:
17+
Input:
18+
5
19+
/ \
20+
3 6
21+
/ \ \
22+
2 4 7
23+
24+
Target = 9
25+
26+
Output: True
27+
Example 2:
28+
Input:
29+
5
30+
/ \
31+
3 6
32+
/ \ \
33+
2 4 7
34+
35+
Target = 28
36+
37+
Output: False
38+
```
39+
40+
## 解题方案
41+
42+
> 思路 1
43+
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******
44+
45+
46+
inorder遍历是O(N),后面的二分是O(lgN),总的时间复杂度为O(N)
47+
48+
```python
49+
class Solution(object):
50+
def findTarget(self, root, k):
51+
"""
52+
:type root: TreeNode
53+
:type k: int
54+
:rtype: bool
55+
"""
56+
def inorder(root):
57+
if not root:
58+
return
59+
inorder(root.left)
60+
nums.append(root.val)
61+
inorder(root.right)
62+
63+
nums = []
64+
inorder(root)
65+
l, r = 0, len(nums) - 1
66+
while l < r:
67+
if nums[l] + nums[r] == k:
68+
return True
69+
elif nums[l] + nums[r] < k:
70+
l += 1
71+
else:
72+
r -= 1
73+
return False
74+
```
75+
76+
77+
78+
79+
80+
81+
82+
83+
84+
85+

0 commit comments

Comments
 (0)