POJ 2418 Java
2010-05-29 01:13
260 查看
开始用基于数组的二叉搜索树来做,由于给的数据建立的树不一定是平衡的,所以很容易发生数组越界,提交了几次都是Runtime Error,因此决定改用基于指针的树结构,结果一次AC了...还是很菜,还要努力。
贴出代码,希望能得到各位大牛指点,也希望能帮助被这题困扰的人,RE还是挺郁闷的......
贴出代码,希望能得到各位大牛指点,也希望能帮助被这题困扰的人,RE还是挺郁闷的......
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { //树节点 public static class TreeNode{ //树种的名字 private String species; private TreeNode left; private TreeNode right; //该树种出现的次数 private int count; } public static class Tree{ //该区域树的总数 private int total; private TreeNode root=new TreeNode(); public void insert(String newSpecies,TreeNode root){ //树为空 if(root.count==0){ root.species=newSpecies; root.count++; total++; return; } else{ //比该结点小 if(root.species.compareTo(newSpecies)>0){ if(root.left==null){ root.left=new TreeNode(); } insert(newSpecies,root.left); }else{ if(root.species.compareTo(newSpecies)<0){ if(root.right==null){ root.right=new TreeNode(); } insert(newSpecies,root.right); }else{ root.count++; total++; } } } } //树的遍历输出(中序) public void travelTree(TreeNode root){ if(root==null){ return; } travelTree(root.left); System.out.print(root.species+" "); double p=(double)root.count*100/total; //控制输出精度 System.out.printf("%.4f", p); System.out.println(); travelTree(root.right); } } public static void main(String[] args){ BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); Tree t=new Tree(); String s; try { while((s=reader.readLine())!=null){ //本地测试用 // if(s.compareTo("0")==0){ // // break; // // } // System.out.println(s); t.insert(s,t.root); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println("total: "+t.totalCount); t.travelTree(t.root); } }
相关文章推荐
- poj 2418 字典树 Map容器
- poj 2418 Hardwood Species(二叉排序树)
- JAVA大数求余 Basic remains(POJ 2305)
- POJ 2418 Hardwood Species
- poj1001 Exponentiation(JAVA实现)
- poj 2305 Basic remains java
- poj 上用java写代码的模板
- POJ系列——java
- POJ 2418--Hardwood Species【map】
- POJ 1503 Integer Inquiry【大数相加 java】
- poj 2418(trie树其实用map可能水过)
- (使用STL自带的排序功能7.1.1)POJ 2418 Hardwood Species(map的定义、访问、迭代)
- POJ-3617-Best Cow Line(贪心算法+Java)
- poj 2418 Hardwood Species 排序二叉树
- poj 2265 java
- poj 2506 java
- poj 2418 Hardwood Species
- poj 3026 Borg Maze(java bfs + prim)
- poj 1503 第一个java
- poj2418 二叉排序树