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.
Example 1:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True

这道题其实和是不是BST关系不大,因为并不是寻找某一个值,所以还是要遍历整个树,思路和在数组中寻找两个和为给定值的元素的思路差不多

/**
 * 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) {
        if(root == null)
            return false;

        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        HashSet<Integer> set = new HashSet<Integer>();
        queue.offer(root);

        while(queue.size() > 0) {
            TreeNode temp = queue.poll();
            if(set.contains(temp.val))
                return true;

            set.add(k - temp.val);
            if(temp.left != null)
                queue.offer(temp.left);
            if(temp.right != null)
                queue.offer(temp.right);
        }

        return false;
    }
}

results matching ""

    No results matching ""