簡體   English   中英

我想做一個樹狀圖結構。 我想找到一棵先前的樹

[英]I want to make a treemap structure. And I want to find a previouse tree

class Fran
{
  String name;
  int size;

  Fran(String name,int size)
  {  this.name=name;  this.size=size;  }

  String getName()
  {  return this.name;  }

  int getSize()
  {  return this.size;  }
}

class Node
{
    Fran fran;
    Node preNode;

    Node[] children=new Node[10];
    int childCount=0;
    Node child;

    /*  is there child?  */
    int isChild=0;

    Node(Fran fran)
    {
       this.fran=fran;
    }

    Node(Node preNode,Fran fran)
    {
      this.fran=fran;
      this.preNode=preNode;
    }

    void setChild(Node preNode,Node child)
    {
        this.preNode=preNode;
        this.child=child;
        this.children[childCount]=child;
        this.isChild=1;
        this.childCount++;
    }

    int getChildCount()
    {  return childCount;  }

    Node preNode()
    {  return this.preNode;  }

    String[] getName()
    {
        String[] t=new String[childCount];

        if(childCount==0)  {
            t[0]=this.fran.getName();
            return t;
        }
        else 
        {  
            for(int i=0;i<=childCount-1;i++)
            {
               t[i]=children[i].fran.getName();
            }
            return t;
        }
    }

    int[] getSize()
    {
      int[] t=new int[childCount];

      if(childCount==0)  {
        t[0]=this.fran.getSize();
        return t;
      }
      else 
      {
        for(int i=0;i<=childCount-1;i++)
        {
           t[i]=children[i].fran.getSize();
        }
      return t;
      }
    }

    String getN()
    {
       return this.fran.getName();
    }
}

void setup() 
{
  Fran aa=new Fran("apt",36);
  Fran bb=new Fran("bpt",26);
  Fran cc=new Fran("cpt",16);
  /*  Fran dd=new Fran("dpt",56);  */

  Node a=new Node(aa);
  Node b=new Node(bb);
  Node c=new Node(cc);

  a.setChild(a,b);
  a.setChild(a,c);

  print(a.getN());

  Node f=b.preNode();
  print(f.getN());
}
  • 我想做一個樹狀結構。 我想返回一個previouse節點。
  • 節點 a->b, a->c 。 我想讓 b.preNode() -> Node a。
  • 但是我有 NullpointerException,我該如何解決這個問題?

謝謝

首先,你必須清楚地決定你想要做什么。 你根本沒有說清楚。 a 是根,b 和 c 是它的孩子嗎? 或者a是根,b是它的孩子,c是b的孩子?

您需要一個將子節點添加到節點的 add 方法:

Node a = new Node (...);
Node b = new Node(...);
a.add(b); // this should hook them together

add 方法應該將 b 的父級設置為 a,並將 a 的子級設置為 b。

此外,請注意您有一些文體錯誤。 您應該刪除所有代碼設置變量並將它們放在構造函數中。 目前很難看到創建節點時會發生什么,因為代碼遍布整個班級。

您還應該考慮刪除 Fran 類並將數據放入 Node.js 中。 為什么有兩個班級? 它增加了開銷、復雜性,並且似乎沒有實現任何目標。 這只是風格,但它會清理你的代碼很多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM