A similar question was asked here on SO: [BST with duplicates
User Sazzadur Rahaman posted the three scenarios for accomplishing BST with duplicates, but I need to know how to implement the third situation he mentioned which looks something like this:
Assume we are using the input: "RABSAB."
The tree with the counter variable in brackets would look like this:
R(1)
/ \
/ \
A(2) S(1)
\
\
B(2)
So basically, I want each element(node) to have a specific counter variable.
Is what I'm trying to do possible to implement in just my insert method? Or would I need some sort of other method in my BSTTree/Node class?
****EDIT** my BSTNode class, made changes from Compass's
recommendations.
public class BSTNode {
String key;
BSTNode left, right;
int count=1;
public BSTNode(String key) {
this.key = key;
}
public void insert(String x) {
if (x.compareTo(this.key) > 0) {
if (right != null) {
right.insert(x);
} else {
right = new BSTNode(x);
}
} //Go right
else if (x.compareTo(this.key) < 0) {
if (left != null) {
left.insert(x);
} else {
left = new BSTNode(x);
}
} //Go left
else if (x.compareTo(this.key) == 0) {
count++;
} // It's a duplicate, update the count
}
}
EDIT, updated my output incrementing a counter like that doesn't seem to give the correct output, I'm inserting "RABSAB"
and trying to count the number of duplicate nodes.
Inserting as follows:
String line = "R A B S A B";
String[] words = line.split(" ");
for (int i = 0; i < words.length; i++) {
t1 = t1.Insert(words[i], t1);
System.out.println(words[i] + " : " + t1.count);
}
I get the following output:
R : 1
A : 1
B : 1
S : 1
A : 1
B : 1
Thanks for your time everyone.