C++ clean solution (set) time: O(n), space: O(n)

  • 0

    If the tree is not BST, it also works.

    bool findTarget(TreeNode* root, int k) {
            unordered_set<int> s;
            return help(root, k, s);
        bool help(TreeNode* n, int k, unordered_set<int>& s){
            if(!n) return false;
            if(s.find(n->val) != s.end()) return true;
                s.insert(k - n->val);
                return help(n->left, k, s) || help(n->right, k, s);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.