我有3種遞歸實現的方法。是的,這是爲了學校,所以請,簡單的答案&,我會很感激描述性的答案,所以我可以學習!我對樹結構很陌生。Java中基於ArrayList的二叉樹實現
3種方法如下...
public class Zombies{
public static int countPeople(Person p){...}
// counts all the people in the tree structure
// starting with Person p.
public static int countZombies(Person p){...}
// counts all the people in the tree structure
// starting with Person p that are zombies
public static void draw(Person p){...}
// draws a diagram of the people in tree structure
// starting with Person p.
// each person will be denoted by a P and
// person that is a zombie will be denoted by a Z
//
// The diagram should illustrate the family tree
// structure. Each person will be drawn with 3 minus
// signs '-' for each level below p.
我開始我的Person類和我有幾個問題。
1)我在正確的軌道上我個人類
2)在方法描述中提及二叉樹的樹形結構?
3)我缺少的是能夠實現這些方法(如果有什麼,還是有這種樹形結構需要積木)
下面是我的Person類。類型的樹的
public class Person{
public int id; // some identification number unique to the person
public boolean zombie; // true if the person is a zombie
public char state; // p means human, z means zombie
public ArrayList<Person> friends; // list of friends
public Person(int id, char state, boolean zombie){
this.id = id;
this.state = state;
this.zombie = zombie;
}
public boolean isZombie() {
if (state == 'p'){
return zombie=false;
}
else if (state == 'z'){
return zombie=true;
}
return zombie;
}
}
樣本輸出如下..
P (this is Person q)
---P (this is a friend of q, say q1)
------P (this is a friend of q1)
------Z (this is another friend of q1, who is a zombie)
---Z (this is a friend of q, say q2, who is a zombie)
------Z (this is a friend of q1, who is also a zombie)
------P (this is a friend of q1, who is not a zombie)
預先感謝耐心和幫助/輸入!
目前尚不清楚這是否是一個樹狀結構:在一棵樹中,這種關係是不對稱的,就像親子一樣;但如果你是我的朋友,我不是你的朋友嗎?除非你的朋友實現是單向的,否則這不是一棵樹。此外,它不是二元的,除非你打算把「朋友」的大小限制在2. – miorel
@miorel謝謝!所以基本上我只是讓它在繪圖函數中「出現」爲一棵樹? – choloboy7
既然你有一個面向對象的編程標籤,我想建議你創建一個擴展Person的殭屍類。然後,您可以使用「實例」進行適當的檢查,而不是使用布爾值並且函數isZombie。面向對象是強大的。 – RyPope