Leetcode / 653. Two Sum IV - Input is a BST
Pick a programming language:
Here is the source code for the solution to this problem.
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
HashSet<Integer> hashSet = new HashSet<Integer>();
// You can also use a queue for breadth-first
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode curr = stack.pop();
int difference = k - curr.val;
if (hashSet.contains(difference)) {
return true;
}
hashSet.add(curr.val);
if (curr.left != null) {
stack.push(curr.left);
}
if (curr.right != null) {
stack.push(curr.right);
}
}
return false;
}
}
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: