LeetCode Question: 653. Two Sum IV - Input is a BST (Level : Easy)
Problem Statement: Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
Note:- Scroll horizontally to see the full line of code.
/**
*Definition for a binary tree node.
*struct TreeNode {
* int val;
* TreeNode * left;
* TreeNode * right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
*};
*/
class Solution
{
vector<int> elements;
public:
void preorder(TreeNode *root)
{
if (root->left)
{
preorder(root->left);
}
if (root->right)
{
preorder(root->right);
}
elements.push_back(root->val);
}
bool findTarget(TreeNode *root, int k)
{
if (root)
{
preorder(root);
}
int n = elements.size();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i != j && elements[i] + elements[j] == k)
{
return true;
}
}
}
return false;
}
};
Comments
Post a Comment