给定一个二叉搜索树的 根节点 root 和一个整数 k , 请判断该二叉搜索树中是否存在两个节点它们的值之和等于 k 。假设二叉搜索树中节点的值均唯一。
示例 1:
输入: root = [8,6,10,5,7,9,11], k = 12
输出: true
解释: 节点 5 和节点 7 之和等于 12
示例 2:
输入: root = [8,6,10,5,7,9,11], k = 22
输出: false
解释: 不存在两个节点值之和为 22 的节点
提示:
二叉树的节点个数的范围是 [1, 104].
-104 <= Node.val <= 104
root 为二叉搜索树
-105 <= k <= 105
中序遍历+哈希
class Solution {
public boolean findTarget(TreeNode root, int k) {
Set<Integer> set = new HashSet<>();
Deque<TreeNode> stack = new ArrayDeque<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
TreeNode node = stack.poll();
if (set.contains(k - node.val)) return true;
set.add(node.val);
root = node.right;
}
}
return false;
}
}
dfs+哈希
class Solution {
Set<Integer> set = new HashSet<>();
public boolean findTarget(TreeNode root, int k) {
if (root == null) return false;
if (set.contains(k-root.val)) return true;
set.add(root.val);
boolean left = findTarget(root.left,k);
boolean right = findTarget(root.right,k);
return left || right;
}
}
中序遍历 + 双指针
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
//利用bst中序遍历有序特性,利用双指针来实现,可以用左右两个栈来实现左右两个指针
public boolean findTarget(TreeNode root, int k) {
TreeNode tem = root;
Deque<TreeNode> ls = new LinkedList<>(), rs = new LinkedList<>();
while (tem != null) {
ls.addLast(tem);
tem = tem.left;
}
tem = root;
while (tem != null) {
rs.addLast(tem);
tem = tem.right;
}
//此时左右两个栈分别存放的是最小值和最大值
TreeNode l = ls.peekLast(), r = rs.peekLast();
while (l.val < r.val) {
int t = l.val + r.val;
if (t == k) return true;
if (t < k) l = getNext(ls, true);
else r = getNext(rs, false);
}
return false;
}
TreeNode getNext(Deque<TreeNode> stk, boolean flag) {
TreeNode node = flag ? stk.pollLast().right : stk.pollLast().left;
while (node != null) {
stk.addLast(node);
//左子树就要找下一个大的,右子树找上一个大的
node = flag ? node.left : node.right;
}
return stk.peekLast();
}
}