Description:
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
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
题意:计算在一颗二叉搜索树中能否找到两个节点,使得这两个节点的节点值之和与指定的元素相同;
解法:要在一个序列中找到两个数num1,num2之和为指定的元素target,换个角度想,就是计算能否找到target-num2这个元素;因此,我们可以遍历二叉树(前序,中序,后序或者层次遍历都可以)将所有节点值存储在表中;之后,对表中每个节点值num,判断在表中是否存在另外一个元素target-num(并且这个元素和num不是同一个元素);
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Set<Integer> nodes = new HashSet<>();
public boolean findTarget(TreeNode root, int k) {
storeTreeNode(root);
Iterator<Integer> it = nodes.iterator();
while (it.hasNext()) {
int first = it.next();
if (nodes.contains(k - first) && first != (k - first)) {
return true;
}
}
return false;
}
private void storeTreeNode(TreeNode root) {
if (root == null) return;
nodes.add(root.val);
storeTreeNode(root.left);
storeTreeNode(root.right);
}
}