欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 设计一个Hero二叉树,HeroNode. 可以向这个英雄二叉树插入不同的Hero对象,并且按照Hero的血量升排序。 随机生成10个Hero对象,每个Hero对象都有不同的血量值,插

程序员文章站 2022-04-06 13:20:26
public class Hero implements {public String name ;public float hp;public Hero(){}public Hero(String name,float hp){this.name = name;this.hp = hp;}public String toString(){return "name:"+name+"\t"+"hp:"+ hp+"\n";}}package col....

public class Hero implements  {

	public String name ;
	public float hp;

	public Hero(){}
	
	public Hero(String name,float hp){
		this.name = name;
		this.hp = hp;
	}
	public String toString(){
		return "name:"+name+"\t"+"hp:"+ hp+"\n";
	}
}
package collection;
import java.util.List;
import java.util.ArrayList;
import file.Hero;
public class HeroNode{
	
	public HeroNode leftNode;
	public HeroNode rightNode;
	public Hero hero;
	
	public void add(Hero h){
		if(null==hero){
			hero = h;
		}
		else{
			if(hero.hp>=h.hp){
				if(null==leftNode)
					leftNode = new HeroNode();
				leftNode.add(h);
			}
			else{
				if(null==rightNode)
					rightNode = new HeroNode();
				rightNode.add(h);
			}
		}
		
	}
	public List<Object> values(){
		List<Object> value = new ArrayList<>();
		if(leftNode!=null)
			value.addAll(leftNode.values());
		value.add(hero);
		if(null!=rightNode)
			value.addAll(rightNode.values());
		return value;
	}
	public static void main(String[] args){
		Hero heros[] = new Hero[10];
		for(int i=0;i<10;i++){
			heros[i] = new Hero("hero"+i, (float)(Math.random()*100));
			System.out.println(heros[i]);
		}
		HeroNode hn = new HeroNode();
		for(int i=0;i<10;i++){
			hn.add(heros[i]);
		}
		System.out.println(hn.values());
	}
}


本文地址:https://blog.csdn.net/qq_37758122/article/details/107335847