3
int countNodes(TreeNode *root) {7
return countNodes(root->left) + countNodes(root->right) + 1;10
bool findTarget(TreeNode *root, int k) {11
int totalCount = countNodes(root);13
stack<TreeNode *> inorder;14
stack<TreeNode *> revInorder;16
TreeNode *currNode = root;17
while (currNode != NULL) {18
inorder.push(currNode); // Store all elements in left of tree19
currNode = currNode->left;23
while (currNode != NULL) {24
revInorder.push(currNode); // Store all elements in right of tree25
currNode = currNode->right;28
while (count < totalCount - 1) {29
TreeNode *inordertop = inorder.top();30
TreeNode *revinordertop = revInorder.top();31
if (inordertop->val + revinordertop->val == k) { // If inordertop + revinordertop is equal to32
// k, we have found a pair, so return true34
} else if (inordertop->val + revinordertop->val >35
k) { // If they are greater than k, we have to found a value36
// which is just smaller than revinordertop, which means we have to find37
// predecessor of revinordertop, as we have to reduce the sum to make it39
TreeNode *currtop = revinordertop;43
currtop = currtop->left;45
revInorder.push(currtop);46
currtop = currtop->right;50
// If they are smaller than k, we have to found a value which is just51
// larger than inordertop, which means we have to find successor of52
// revinordertop, as we have to increase the sum to make it equal to k53
TreeNode *currtop = inordertop;57
currtop = currtop->right;59
inorder.push(currtop);60
currtop = currtop->left;