My C++ non-recursive solution using unordered_set and stack


  • 3
        bool findTarget(TreeNode* root, int k) {
            unordered_set<int> s;
            stack<TreeNode*> q;
            q.push(root);
            TreeNode *temp;
            while(q.size())
            {
                temp = q.top();
                q.pop();
                if(temp){
                    if(s.count(k-temp->val)) return true;
                    else s.insert(temp->val);
                    if(temp->right) q.push(temp->right);
                    if(temp->left) q.push(temp->left);
                }
            }
            return false;
        }
    

Log in to reply
 

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