英雄二叉树:设计一个Hero二叉树,HeroNode.可以向这个英雄二叉树插入不同的Hero对象,并且按照Hero的血量倒排序。随机生成10个Hero对象,每个Hero对象都有不同的血量值,插入这个HeroNode后,把排序结果打印出来。
package set;
import java. util. ArrayList;
import java. util. List;
public class HeroNode {
public HeroNode leftNode;
public HeroNode rightNode;
private Hero value;
public void add ( Hero hero) {
if ( value== null) {
value= hero;
} else if ( ( Integer) hero. gethp ( ) < ( Integer) value. gethp ( ) ) {
if ( leftNode== null) {
leftNode= new HeroNode ( ) ;
}
leftNode. add ( hero) ;
} else {
if ( rightNode== null) {
rightNode= new HeroNode ( ) ;
}
rightNode. add ( hero) ;
}
}
public List< Hero> hp ( ) {
List< Hero> hps= new ArrayList < Hero> ( ) ;
if ( rightNode!= null) {
hps. addAll ( rightNode. hp ( ) ) ;
}
hps. add ( value) ;
if ( leftNode!= null) {
hps. addAll ( leftNode. hp ( ) ) ;
}
return hps;
}
public static void main ( String[ ] args) {
ArrayList< Hero> heros= new ArrayList < Hero> ( ) ;
for ( int i= 0 ; i< 10 ; i++ ) {
heros. add ( new Hero ( "hero " + i, ( int ) ( Math. random ( ) * 1000 ) ) ) ;
}
System. out. println ( "随机生成的Hero序列为:" ) ;
System. out. println ( heros) ;
HeroNode heronodes= new HeroNode ( ) ;
for ( Hero k: heros) {
heronodes. add ( k) ;
}
System. out. println ( "倒序输出为:" ) ;
System. out. println ( heronodes. hp ( ) ) ;
}
}
package set;
public class Hero {
private String str;
private int hp;
public Hero ( ) {
}
public Hero ( String name) {
this . str= name;
}
public Hero ( String name, int hp) {
this . hp= hp;
this . str= name;
}
public int gethp ( ) {
return hp;
}
@Override
public String toString ( ) {
return "name: " + str+ " " + "hp: " + hp;
}
}