问题描述:
Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
查找二叉树中是否有两个相加等于k的元素
思路:
DFS+hashset
代码如下:
class Solution {
public boolean findTarget(TreeNode root, int k) {
Set<Integer> set=new HashSet<>();
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode currentNode=stack.pop();
if(set.contains(k-currentNode.val)) return true;
set.add(currentNode.val);
if(currentNode.left!=null){
stack.push(currentNode.left);
}
if(currentNode.right!=null){
stack.push(currentNode.right);
}
}
return false;
}
}
时间复杂度:O(n)