先了解一下二叉搜索树(BST)的概念
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
注释:二叉查找树中没有值相同的两个节点,但在实际应用中可能会出现值相同的情况,这时就要看具体的需求了,如果你实际应用中允许相同的值,那么向左向右插入都可以,你只要保证你的树在中序遍历时是非严格单调递增即可。如果你实际应用中要求值唯一,那么你的实现应该以某种形式告诉用户,比如说返回某个特殊值,或者抛出异常。
方法一:递归
public static boolean findTarget(TreeNode root, int k) {
if (root == null) return false;
HashSet<TreeNode> hashSet = new HashSet<>();
return helper(root, k, hashSet);
}
public static boolean helper(TreeNode treeNode, int k, HashSet hashSet) {
if (treeNode == null) return false;
if (hashSet.contains(k - treeNode.val)) return true;
hashSet.add(treeNode.val);
return helper(treeNode.left, k, hashSet) || helper(treeNode.right, k, hashSet);
}
方法二:迭代
public static boolean findTarget(TreeNode root, int k) {
if (root == null) return false;
HashSet<Integer> hashSet = new HashSet<>();
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (hashSet.contains(root.val)) return true;
else hashSet.add(k - root.val);
root = root.right;
}
return false;
}
个人感觉递归方法简单明了。