Leetcode 653. Two Sum IV - Input is a BST Why we need set?

Viewed 9

I don't understand why how HashSet works in this question Here's the link to this problem https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ Here's the solution to this problem enter image description here

the codes are

public class Solution {
public boolean findTarget(TreeNode root, int k) {
    Set < Integer > set = new HashSet();
    Queue < TreeNode > queue = new LinkedList();
    queue.add(root);
    while (!queue.isEmpty()) {
        if (queue.peek() != null) {
            TreeNode node = queue.remove();
            if (set.contains(k - node.val))
                return true;
            set.add(node.val);
            queue.add(node.right);
            queue.add(node.left);
        } else
            queue.remove();
    }
    return false;
 }
 }

Why we need to declare another HashSet for this problem? Do we put all the tree node in the hashset? Why this step is not shown in the code?

Also, since we didn't explicitly put any value in the set, how can we code for "set. contains()"? Am I missing some basics for hashset?

From the code, we simply traversed the tree using an extra queue and then we add the valid value/answer into the hashset. But we only need to return the boolean answer for this question. Thats why I am confused.

0 Answers
Related