<p>Given the <code>root</code> of a binary search tree and an integer <code>k</code>, return <code>true</code> <em>if there exist two elements in the BST such that their sum is equal to</em> <code>k</code>, <em>or</em> <code>false</code> <em>otherwise</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/21/sum_tree_1.jpg" style="width: 400px; height: 229px;" />
<pre>
<strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9
<strong>Output:</strong> true
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/21/sum_tree_2.jpg" style="width: 400px; height: 229px;" />
<pre>
<strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28
<strong>Output:</strong> false
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>
	<li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li>
	<li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li>
</ul>

/**
 * Definition for a binary tree TreeNode.
 * struct TreeTreeNode {
 *     int val;
 *     TreeTreeNode *left;
 *     TreeTreeNode *right;
 *     TreeTreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeTreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeTreeNode(int x, TreeTreeNode *left, TreeTreeNode *right) : val(x), left(left), right(right) {}
 * };
 */


class BstIterator {
private:
    stack<TreeNode*> st;
    bool reverse = true;
    // reverse = true -> before pointer
    // reverse = false -> next pointer

public:
    BstIterator(TreeNode* root,bool isReverse) {
        reverse = isReverse;
        pushAll(root);
    }

    bool hasNext() {
        return !st.empty();
    }

    int next(){
        TreeNode* top = st.top();
        st.pop();
        if(reverse) {
            pushAll(top->left);
        }
        else {
            pushAll(top->right);
        }

        return top->val;
    }

private:
    void pushAll(TreeNode* root) {
        while(root != NULL) {
            st.push(root);

            if(reverse) {
                root = root->right;
            }
            else {
                root = root->left;
            }

        }
    }
};


class Solution {
public:
    bool findTarget(TreeNode* root,int k) {
        if(root == NULL) {
            return false;
        }

        BstIterator left(root,false);
        BstIterator right(root,true);

        int i = left.next();
        int j = right.next();

        while(i < j) {
            if(i + j == k) {
                return true;
            }
            else if(i + j < k) {
                i = left.next();
            }
            else {
                j = right.next();
            }
        }

        return false;
    }
};
37100