2012-09-10 24 views
-1

我想實現二叉樹,但是我在傳遞方法時遇到困難。這是我的代碼: 有兩個單獨的類:xyzBTreeBTree的方法正在使用xyz的方法test在不使用預定義函數的情況下實現二叉樹

class xyz{ //main class 
    public static void main (String args[]){ 
    xyz obj = new xyz(); 
    obj.test(n); //takes input (int) from user 
    } 

    public void test(int n){ 
     BTree p = new BTree(); 
     int d1 = p.depth( //I want ot pass a node here); 
      //My question: How to pass an argument here as "Node" to be received properly by the method?? 
     .... 
     .... 
    } 
} 
class BT Tree{  //another different class 
    private Node root; 
    private Node node; 
    private int size; 
    public static class Node { 
     Node left; 
     Node right; 
     Node back; 
     int data; 
     int index; 

    Node(int newindex) { 
     left = null; 
     right = null; 
     back= null; 
     data = 0; 
     index = newindex; 
    } 
} 
    public void BTree() { //constructor 
     root = null; 
    } 

    public int depth(Node node){  //Node pass will be correctly executed here 
     if (node.index==root.index) 
      return 0; 
     else 
      return 1+depth(parent(node)); 
    } 
} 

我的問題是:如何通過depth()方法傳遞一個節點?

+2

爲什麼不'depth'和'parent'方法*裏面*'Node'?他們爲什麼應該在'BTree'? (PS在二叉樹和[B-tree](http://en.wikipedia.org/wiki/B-tree)之間有區別) – oldrinb

+0

我相信你需要一個公共的無參數'depth()'方法這將調用私有'深度(節點節點)'方法以根節點爲參數。如前所述,每個節點都應該跟蹤它的深度。 –

回答

0

我的問題是:如何通過depth()方法傳遞一個節點?

目前還不清楚BTree課程的設計是否旨在隱藏Node對象。

  • 如果Node目的並沒有被隱藏,那麼答案是「你通過它就像任何其他對象的引用」。這引出了你從哪裏得到節點引用的問題,並且答案是你的類必須提供允許外部代碼(例如你的類xyz類)獲得節點引用的方法。這也意味着您的depth方法需要考慮到Node目前不是「此」BTree的成員的可能性。

  • 如果要隱藏對象Node,那麼在您的depth(Node)方法中存在問題。

    • 如果外部呼叫代碼無法獲得Node將此設置爲公共方法的意義何在?它應該是一種私人方法嗎?
    • 它應該是一個公共方法,但是具有不同的語義?例如,它應該給出樹中任何節點的最大深度,而不是給定節點的深度? (注:即​​的實施將需要完全不同的......)