我有1000个数字,我制作一棵二叉树并对树进行排序。它打印0到100和其他899号码是重复的。我如何跟踪每个号码的频率。例如,28号出现9次。以某种方式保持计数。我一直在使用一种方法,但是如果它接近或不接近,我会使用Idk。我会在最后发布该方法。如何查找重复的数字并显示该数字的频率
public class bigTree {
int data;
int frequency;
bigTree Left, Right;
public bigTree makeTree(int x) {
bigTree p;
p = new bigTree();
p.data = x;
p.Left = null;
p.Right = null;
return p;
}
public void setLeft(bigTree t, int x) {
if (t.Left != null) {
// setLeft(t.Left, x);
System.out.println("Error");
}
else {
t.Left = makeTree(x);
}
}
public void setRight(bigTree t, int x) {
if (t.Right != null) {
//setRight(t.Right, x);
System.out.println("Error");
} else {
t.Right = makeTree(x);
}
}
public void insertLocation(bigTree tree, int v) {
// if (tree.data == v) {
//findDuplicate(v);
//}
if (v < tree.data) {
if (tree.Left != null){
insertLocation(tree.Left, v);
}
else {
setLeft(tree, v);
}
}
if (v > tree.data) {
if (tree.Right != null){
insertLocation(tree.Right, v);
} else {
setRight(tree, v);
}
}
}
public void sort(bigTree t) {
if (t.Left != null) {
sort(t.Left);
}
System.out.println(t.data + " freq = " + frequency);
if (t.Right != null) {
sort(t.Right);
}
}
public void dealArray(String[] x) {
int convert;
bigTree tree = makeTree(Integer.parseInt(x[0]));
for (int i = 1; i < x.length; i++){
//convert = Integer.parseInt(x[i]);
insertLocation(tree, Integer.parseInt(x[i]));
findDuplicate(Integer.parseInt(x[i]));
} sort(tree);
}
----我认为可以工作的方法,但是,这不是----
public void findDuplicate(int number) {
bigTree tree, h, q;
tree = makeTree(number);
//while (//there are #'s in the list) { //1st while()
h = tree;
q = tree;
while (number != h.data && q != null) { //2nd while()
h = q;
if (number < h.data) {
q = q.Left;
} else {
q = q.Right;
}
} //end of 2nd while()
if (number == h.data) {
//h.frequency++;
System.out.println("Duplcate: " + number + "freq = " + h.frequency++);
}
else {
if (number < h.data) {
setLeft(h,number);
}
else {
setRight(h, number);
}
}
//} // End of 1st while()
sort(h);
}
你能解释一下当你说方法不起作用时你的意思吗? –
听起来像家庭作业..我会使用一个地图与数字作为关键,并出现的次数作为价值。 – Laf
如果这是家庭作业,它需要被标记为这样。 – Thom