File tree Expand file tree Collapse file tree 1 file changed +85
-0
lines changed
docs/Leetcode_Solutions/Python Expand file tree Collapse file tree 1 file changed +85
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments