2016-04-28 39 views
0

正如標題所示,我需要幫助在二進制樹中查找最大值。我試圖用遞歸來做到這一點。查找二進制樹中的最大值並返回該節點

節點有一個頻率實例變量,如果節點中的元素在樹中是重複的,並且它是最大值即時嘗試達到,但我只是得到一個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); 
    } 

} 

請幫幫我!

+0

你也可以發佈Node類嗎? –

+0

已更新@ user3747720 – JohnBanana

回答

0

getMaxFreq(node.left);和其他類似位置前添加return陳述。我完全不瞭解您的代碼,但您從不使用遞歸調用的結果。也許你應該將它們保存爲變量並將它們相互比較。

0

在使用leftright之前,您沒有檢查null。最終你遇到節點誰沒有離開,或權利,或任何一方。你需要檢查,因爲左/右是空你 - 顯然 - 不應該費心檢查或遍歷任何這樣的節點,因爲在那裏沒有節點。

+0

您可以評估更多一點嗎?即時通訊都卡在這裏。 – JohnBanana

+0

@JohnBanana不,我不能。這就是你需要的一切:在你嘗試使用對象引用之前 - 比如你在行中做if(left.compareTo(right)> 0){' - 你必須**檢查它是不是' null「,否則程序會拋出你得到的例外。 – MichaelK