C++ recursive using BST property and no augmenting data structures (35ms)


  • 0
    M

    Like the usual two-sum, this takes each value in the collection and looks for the difference between that node's value and the target value. This could result in N failed look ups, each of which may traverse the height of the tree.

        bool findTarget(TreeNode* root, int k) {
            return findTarget(root, root, k);
        }
    
        bool findTarget(TreeNode* root, TreeNode* curr, int k)
        {
            if (!curr) return false;
            auto diff = k - curr->val;
    
            // BST search for value difference starting at the root
            auto node = root;
            while (node) {
                if ((node != curr) && (node->val == diff))
                        break;
    
                if (node->val > diff)
                    node = node->left;
                else
                    node = node->right;
            }
    
            // found the value difference
            if (node && (node->val == diff))
                return true;
    
            // didn't find; traverse left and right
            return
                findTarget(root, curr->left, k) ||
                findTarget(root, curr->right, k);
        }
    

Log in to reply
 

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