|
| 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 | + |
0 commit comments