Fork me on GitHub

Two Sum IV - Input is a BST

Description

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
unordered_map<int, int> mapping;
if (root == NULL || (root->left ==NULL && root->right == NULL)) return false;
bool ret = false;
helper(mapping, root, k, ret);
return ret;
}

void helper(unordered_map<int, int>& mapping, TreeNode* root, int k, bool& ret) {
if (ret || root == NULL) return;
if (mapping.count(k - root->val) != 0) {ret = true; return;}
mapping[root->val] = 1;
helper(mapping, root->right, k, ret);
helper(mapping, root->left, k , ret);
return;
}
};