關於一個樹狀結構的通用類

zingers發表於2003-05-29
因為在網上找不到,所以嘗試自己寫一下。
如果你有網路資源,請告訴我,謝謝。

import java.util.*;

public class TreeModule
{
TreeModule son ;//最左邊的兒子節點
TreeModule bro ;//最左邊的兄弟節點
TreeModule father;


public boolean hasSon()
{
if (son != null)
{
return true;
}
return false;
}

public boolean hasBro()
{
if (bro !=null )
{
return true;
}
return false;
}

public boolean hasFather()
{
if (this.father!=null)
{
return true;
}
return false;
}

public TreeModule getFather()
{
return this.father;
}

public TreeModule getSon()
{
return son;
}

public TreeModule getBro()
{
return bro;
}

public TreeModule getLastson()
{
TreeModule point = this.getSon();
while(point !=null && point.hasBro())
{
point = point.getBro();
}
return point;
}

public TreeModule getLastbro()
{
TreeModule point = this.getBro();
while (point != null && point.hasBro())
{
point = point.getBro();
}
return point;
}



public ArrayList getSons()
{
ArrayList list = new ArrayList();
TreeModule temp = null;
if (this.hasSon())
{
temp = this.getSon();
list.add(temp);
while (temp.hasBro())
{
temp = temp.getBro();
list.add(temp);
}
}
return list;
}



public ArrayList getBrothers()
{
ArrayList list = new ArrayList();
TreeModule temp = this;
while (temp.hasBro())
{
temp = temp.getBro();
list.add(temp);
}
return list;
}





public void addSon(TreeModule a)
{
TreeModule temp = this;
if (temp==null)
return;

if(!temp.hasSon())
{
temp.son = a;
}
else
{
temp=temp.getSon();
while (temp.hasBro())
{
temp=temp.getBro();
}

temp.bro=a;
}

a.father = this;
}


public void addSons(ArrayList list)
{
if (list.size()>=1)
{
for (int j=0;j<list.size() ;j++ )
{
this.addSon((TreeModule)list.get(j));
}
}
}



public void delSon(TreeModule son)
{
ArrayList list = getSons();
for (int i=0;i<list.size() ;i++)
{
if ( ((TreeModule)list.get(i)).equals(son) )
{
((TreeModule)list.get(i-1)).bro=(TreeModule)list.get(i+1);
ArrayList list2 = ((TreeModule)list.get(i)).getSons();
this.addSons(list2);
//list2.get(i) = null;
return;
}
}
}



public void clearSon(TreeModule son)
{
ArrayList list = getSons();
for (int i=0;i<list.size() ;i++ )
{
if ( ((TreeModule)list.get(i)).equals(son) )
{
((TreeModule)list.get(i-1)).bro=(TreeModule)list.get(i+1);
//((TreeModule)list.get(i)).deltree();
return;
}
}
}

public void deltree()
{
ArrayList list = getSons();

if(list.size()==0)
{
/*cant be compiled
this = null;
*/
return;
}

Iterator ite = list.iterator();
TreeModule temp = null;
while (ite.hasNext())
{
temp=(TreeModule)ite.next();
temp.deltree();
}


}

public TreeModule getTop()
{
TreeModule temp = this.father;
if (temp==null)
{
return this;
}
while (temp!=null)
{
temp = temp.father;
}
return temp;
}

}

我感覺有很多問題,特別是在clearSon時記憶體沒清乾淨。
希望大家多提意見。

相關文章