Two Sum IV - Input is a BST Posted on 2018-11-02 Descriptionhttps://leetcode.com/problems/two-sum-iv-input-is-a-bst/ Solution12345678910111213141516171819202122232425262728/** * 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; }};