[LeetCode] Two Sum IV - Input is a BST

Problem

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.node

Example

Example 1:
Input:code

5
   / \
  3   6
 / \   \
2   4   7

Target = 9element

Output: True
Example 2:
Input:get

5
   / \
  3   6
 / \   \
2   4   7

Target = 28it

Output: Falseio

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean findTarget(TreeNode root, int k) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        Set<Integer> set = new HashSet<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (set.contains(k-cur.val)) return true;
            set.add(cur.val);
            if (cur.left != null) queue.offer(cur.left);
            if (cur.right != null) queue.offer(cur.right);
        }
        return false;
    }
}
相關文章
相關標籤/搜索