java2--二叉樹【例】

二叉樹的實例

//2012.7.29
//二叉樹

class Student implements Comparable<Student>{
	int score;
	String name;
	public Student(String name,int score){
		this.name = name;
		this.score = score ; 	
	}
	public int compareTo(Student stu){
		if(this.score>stu.score){
			return 1;	
		}else{
			return -1;	
		}
	}	
	public String toString(){
		return "姓名:" + name + "\t成績:" + score;	
	}
};
class BinaryTree{
	class Node{			// 聲明一個節點類
		private Student data ;	// 保存具體的內容
		private Node left ;			// 保存左子樹
		private Node right ;		// 保存右子樹
		public Node(Student data){
			this.data = data ;
		}
		public void addNode(Node newNode){
			// 確定是放在左子樹還是右子樹
			if(newNode.data.compareTo(this.data)<0){	// 內容小,放在左子樹
				if(this.left==null){
					this.left = newNode ;	// 直接將新的節點設置成左子樹
				}else{
					this.left.addNode(newNode) ;	// 繼續向下判斷
				}
			}
			if(newNode.data.compareTo(this.data)>=0){	// 放在右子樹
				if(this.right==null){
					this.right = newNode ;	// 沒有右子樹則將此節點設置成右子樹
				}else{
					this.right.addNode(newNode) ;	// 繼續向下判斷
				}
			}
		}
		public void printNode(){	// 輸出的時候採用中序遍歷
			if(this.left!=null){
				this.left.printNode() ;	// 輸出左子樹
			}
			System.out.println(this.data.toString()) ;
			if(this.right!=null){
				this.right.printNode() ;
			}
		}
	};
	private Node root ;		// 根元素
	public void add(Student data){	// 加入元素
		Node newNode = new Node(data) ;	// 定義新的節點
		if(root==null){	// 沒有根節點
			root = newNode ;	// 第一個元素作爲根節點
		}else{
			root.addNode(newNode) ; // 確定是放在左子樹還是放在右子樹
		}
	}
	public void print(){
		this.root.printNode() ;	// 通過根節點輸出
	}
};
public class ComparableDemo03{
	public static void main(String args[]){
		BinaryTree bt = new BinaryTree() ;
		bt.add(new Student("as",8)) ;
		bt.add(new Student("b",3)) ;
		bt.add(new Student("c",3)) ;
		bt.add(new Student("d",10)) ;
		bt.add(new Student("e",9)) ;
		bt.add(new Student("f",1)) ;
		bt.add(new Student("g",5)) ;
		bt.add(new Student("h",5)) ;
		System.out.println("排序之後的結果:") ;
		bt.print() ;
	}
};
這個是仿寫的,沒有默寫……但是註釋了好多



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章