2014-02-11 26 views

回答

1

下面是部分代碼註釋:

public class Tree 
{ 
    private Node root; 

    public int findDepth(int searchNodeValue) { 
     List<Node> nodesAtCurrentLevel = Collections.singletonList(root); 

     return recursiveSearch(0, searchNodeValue, nodesAtCurrentLevel); 
    } 

    public int recursiveSearch(int level, int searchNodeValue, List<Node> nodesAtCurrentLevel) { 
     List<Node> nodesAtNextLevel = new ArrayList<Node>(); 

     // Check if searchNode matches any node at current level 
     for (Node node : nodesAtCurrentLevel) { 
      // If it matches, we have found the node, return current level 
      if (node.getValue() == searchNodeValue) { 
       return level; 
      } 

      // Add children of all nodes at current level in nodesAtNextLevel 
      if (node.hasChildren()) { 
       nodesAtNextLevel.addAll(node.getChildren()); 
      } 
     } 

     // searchNode is not found at current level, increment level and continue search at next level if next level exists in tree 
     if (!nodesAtNextLevel.isEmpty()) { 
      return recursiveSearch(level + 1, searchNodeValue, nodesAtNextLevel); 
     } 

     // We have traversed entire tree. Node not found. Return -1 
     return -1; 
    } 
} 

class Node 
{ 
    private int value; 

    private List<Node> children = new ArrayList<Node>(); 

    public Node(int value) { 
     this.value = value; 
    } 

    public boolean hasChildren() { 
     return children.isEmpty(); 
    } 

    public int getValue() { 
     return value; 
    } 

    public List<Node> getChildren() { 
     return children; 
    } 
} 
+0

上面的代碼假設在根級別/深度0 –

+0

非常感謝! – KathyLee

0

編輯

- 有遞歸函數獲取輸入級別。從0/-1開始。返回一個對象;該對象具有節點AND級別。遞歸函數的每一次遞增傳入的級別並將其設置在返回對象中。

- 將級別傳遞給遞歸函數。從0/-1開始。維護一個全局變量(或一個變量,該變量被定義爲非局部於該函數,以便在該函數的每次迭代中都訪問同一個變量;即變量不在堆棧上,而在堆上)我希望這件事很簡單Java並不需要進一步解釋)。在遞歸函數開始時將其設置爲(1 +傳入級別)。這不會是線程安全的。

//原始答案的想法是作爲參考傳遞給關卡,並在遞歸函數中增加它。顯然這在Java中很乏味。

+0

「參照沿着變量傳遞」 - 你知道的問題是關於Java的吧? (我知道有可能在Java中模擬通過引用,但提及通過引用應與解釋和/或鏈接一起) – Dukeling

+0

好的。刪除通過引用位傳遞。替換別的東西。 – Amit