我想返回在二叉树中最常出现的值的数量。我有一个BinaryClass,其中包含许多方法,如add、contain、isEmpty、counter、iterator等。我尝试实现此方法
运行代码时,我遇到了StackOverFlow Exception,请问是否有人可以帮助我?
我对二叉树很陌生,请帮助我。
public int getMaxFrequency()
,但是在标记行处遇到了StackOverFlowException问题。运行代码时,我遇到了StackOverFlow Exception,请问是否有人可以帮助我?
我对二叉树很陌生,请帮助我。
enter code here
public class TreeSetCounter<T extends Comparable<T>> implements Iterable<T>{
public Node<T> root;
int size;
int count=0;
public TreeSetCounter() {
root = null;
size = 0;
}
public int counter(T t) {
return counterRecursive(root, t);
}
public int counterRecursive(Node<T> root, T t) {
int count = 0;
if(root == null) {
return 0;
}
if(root.value.equals(t)) {
count++;
}
count = count + counterRecursive(root.left, t)+ counterRecursive(root.right, t);
return count; }
public int getMaxFrequency(){
return inorder(root);
}
public int inorder( Node<T> prev) {
int count = 1, max = 0;
if (root == null) {
return 0;}
List<T> list = new ArrayList<>();
inorder(root.left); // I get the Exception att this row code.
while (prev != null) {
if (root.value == prev.value)
count++;
else
count = 1;
}
if (count > max) {
max = count;
list.clear();
list.add(root.value);
} else if (count == max) {
list.add(root.value);
}
prev = root;
inorder(root.right);
return max;
}
enter code here
Node.java
public class Node <T>{
T value;
int counter;
Node<T> left;
Node<T> right;
Node(T value, int count) {
this.value = value;
right = null;
left = null;
this.counter= count;
}
enter code here
public static void main(String[] args) {
TreeSetCounter <String> tsc= new TreeSetCounter<String>();
tsc.add("java");
tsc.add("java");
tsc.add("not");
tsc.add("cool");
tsc.add("java");
tsc.add("is");
tsc.add("java");
tsc.add("good");
System.out.println(tsc.getMaxFrequency());}