For the purpose of this problem, the BST is defined to allow duplicates, and the duplicate values will always follow to the right-side of the parent nodes with the same value. For example, with the data:
1, 2, 2, 2, 2
if the root node has the value 2 (as opposed to 1) then the tree will look like:
2
/ \
1 2
\
2
\
2
The following code scans the tree, identifies any values that are duplicated, and prints the duplicate values, as well as how many times that value is duplicated.
public class DuplicateCountInBST {
private TreeNode root;
private class TreeNode {
TreeNode left;
int item;
TreeNode right;
TreeNode (TreeNode left, int item, TreeNode right) {
this.left = left;
this.item = item;
this.right = right;
}
}
private class DuplicateInfo {
int item;
int count;
public DuplicateInfo(int item, int count) {
this.item = item;
this.count = count;
}
}
public void print () {
if (root == null) {
return;
}
// find right most node.
TreeNode rightMostNode = root;
while (rightMostNode.right != null) {
rightMostNode = rightMostNode.right;
}
printHelper (root, root.item, new DuplicateInfo(0, 0), rightMostNode);
}
// inorder traversal
// rightmostnode is a guard against skewed trees.
private void printHelper (TreeNode node, int prevValue, DuplicateInfo duplicateInfo, TreeNode rightMostNode) {
if (node == null) {
return;
}
printHelper(node.left, node.item, duplicateInfo, rightMostNode);
if (node.item == duplicateInfo.item) {
duplicateInfo.item = node.item;
duplicateInfo.count++;
}
if (node.item != duplicateInfo.item || node == rightMostNode) {
if (duplicateInfo.count > 1) {
System.out.println(duplicateInfo.item + " : " + duplicateInfo.count);
}
duplicateInfo.item = node.item;
duplicateInfo.count = 1;
}
printHelper(node.right, node.item, duplicateInfo, rightMostNode);
}
}