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.Example 1:
Input: root = [2,1,3], k = 4
Output: true
Approach
Java
import java.util.ArrayList;import java.util.List;public class TwoSumIVInBST {public static void main(String[] args) {TreeNode root = new TreeNode(2);root.left = new TreeNode(1);root.right = new TreeNode(3);int k = 4;System.out.println(findTarget(root, k));}static List<Integer> v;static boolean findTarget(TreeNode root, int k) {v = new ArrayList<Integer>();inorder(root);int i = 0, j = v.size() - 1;while (i < j) {if (v.get(i) + v.get(j) == k)return true;else if (v.get(i) + v.get(j) > k)j--;elsei++;}return false;}static void inorder(TreeNode root) {if (root == null)return;// call for left subtreeinorder(root.left);// datav.add(root.val);// right subtreeinorder(root.right);}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};vector<int> v;void inorder(TreeNode *root){if (root == NULL)return;//call for left subtreeinorder(root->left);//datav.push_back(root->data);//right subtreeinorder(root->right);}bool findTarget(TreeNode *root, int k){inorder(root);int i = 0, j = v.size() - 1;while (i < j){if (v[i] + v[j] == k)return true;else if (v[i] + v[j] > k)j--;elsei++;}return false;}int main(){TreeNode *root = new TreeNode(2);root->left = new TreeNode(1);root->right = new TreeNode(3);int k = 4;if (findTarget(root, k))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment