正如標題所示,我需要幫助在二進制樹中查找最大值。我試圖用遞歸來做到這一點。查找二進制樹中的最大值並返回該節點
節點有一個頻率實例變量,如果節點中的元素在樹中是重複的,並且它是最大值即時嘗試達到,但我只是得到一個nullpointerexception。這是我的代碼:
private Node getMaxFreq(Node node){
Node left = null;
Node right = null;
if(node == null){
System.out.println("tree is empty");
}
if(node.compareTo(node.left) <= 0){
getMaxFreq(node.left);
}
else{
left = node;
}
if(node.compareTo(node.right) <= 0){
getMaxFreq(node.right);
}
else{
right = node;
}
if(left.compareTo(right) > 0){
return left;
}
else{
return right;
}
}
/**
* method to find the node with highest frequency in tree.
* @return node with highest frequency.
*/
public void getMaxFreq(){
Node temp = root;
System.out.println(getMaxFreq(temp));
}
//Node class
public class Node implements Comparable<Node> {
String word;
int freq;
Node left;
Node right;
Node(String word) {
this.word = word;
freq = 1;
}
public String toString() {
return word + " occurs " + freq + " times.";
}
public int compareTo(Node other) {
return Integer.compare(this.freq, other.freq);
}
}
請幫幫我!
你也可以發佈Node類嗎? –
已更新@ user3747720 – JohnBanana