我们可以将BST的节点放在HashMap或HashSet中吗?如果是这样,我们如何遍历BST。当我解决TWO SUM BST时出现了这种疑问。
答案 0 :(得分:2)
您可以将BinarySearchTree的节点放入HashSet或HashMap(不确定Key,Value对于Map的配对)。对于HashSet,我只是按顺序遍历BST。为了解决你得到的问题,我会解决这个问题:
// Returns true if the BST contains two nodes with elements that
// sum to k, otherwise false
public bool findTarget(TreeNode root, int k){
if(root == null){
throw new NullPointerException();
}
HashSet<Integer> set = new HashSet<Integer>();
return traverse(root, k, set);
}
// Traverses across the BST, in order, adding elements to the set
bool traverse(Node<T> node, int k, HashSet<Node<T>> set){
// If the node has a left child, traverse it first
if(node.left != null){
return traverse(node.left, k, set);
}
// Check to see if the set contains the element that would sum
// with the node we're checking's element to equal k
if(set.contains(k-node.element)){
return true;
}
// Add node's element to the set
set.add(node.element);
// If the node has a right child, traverse it after
if(node.right != null){
return traverse(node.right, k, set);
}
else{
// No two node's with elements summing k exist in the BST,
// since you reached the end and found nothing
return false;
}
}