Skip to content

Commit 2f551be

Browse files
committed
day 23
1 parent 2ea29a0 commit 2f551be

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
Two Sum IV - Input is a BST
3+
===========================
4+
5+
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.
6+
7+
Example 1:
8+
Input: root = [5,3,6,2,4,null,7], k = 9
9+
Output: true
10+
11+
Example 2:
12+
Input: root = [5,3,6,2,4,null,7], k = 28
13+
Output: false
14+
15+
Example 3:
16+
Input: root = [2,1,3], k = 4
17+
Output: true
18+
19+
Example 4:
20+
Input: root = [2,1,3], k = 1
21+
Output: false
22+
23+
Example 5:
24+
Input: root = [2,1,3], k = 3
25+
Output: true
26+
27+
Constraints:
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+
/**
35+
* Definition for a binary tree node.
36+
* struct TreeNode {
37+
* int val;
38+
* TreeNode *left;
39+
* TreeNode *right;
40+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
41+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
42+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
43+
* };
44+
*/
45+
46+
class Solution {
47+
public:
48+
void dfs(TreeNode* root, vector<int>& arr){
49+
if(!root) return;
50+
dfs(root->left, arr);
51+
arr.push_back(root->val);
52+
dfs(root->right, arr);
53+
}
54+
55+
bool findTarget(TreeNode* root, int k) {
56+
vector<int> arr;
57+
dfs(root, arr);
58+
59+
int i=0, j=arr.size()-1;
60+
while(i < j) {
61+
if(arr[i] + arr[j] == k) return true;
62+
else if(arr[i] + arr[j] < k) i++;
63+
else j--;
64+
}
65+
66+
return false;
67+
}
68+
};
69+

Leetcode Daily Challenge/August-2021/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,5 @@
2424
| 19. | [Maximum Product of Splitted Binary Tree](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/615/week-3-august-15th-august-21st/3903/) | [cpp](./19.%20Maximum%20Product%20of%20Splitted%20Binary%20Tree.cpp) |
2525
| 20. | [Valid Sudoku](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/615/week-3-august-15th-august-21st/3904/) | [cpp](./20.%20Valid%20Sudoku.cpp) |
2626
| 21. | [Sudoku Solver](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/615/week-3-august-15th-august-21st/3905/) | [cpp](./20Sudoku%20Solver.%20.cpp) |
27+
| 23. | [Two Sum IV - Input is a BST](https://leetcode.com/explore/featured/card/august-leetcoding-challenge-2021/616/week-4-august-22nd-august-28th/3908/) | [cpp](./23Two%20Sum%20IV%20-%20Input%20is%20a%20BST.cpp) |
28+
| 24. | []() | [cpp](./24.cpp) |

0 commit comments

Comments
 (0)