Java基础部分9

说明生活中遇到的二叉树,用java实现二叉树

这是组合设计模式。

我有很多个(假设10万个)数据要保存起来,以后还需要从保存的这些数据中检索是否存在某个数据,(我想说出二叉树的好处,该怎么说呢?那就是说别人的缺点),假如存在数组中,那么,碰巧要找的数字位于99999那个地方,那查找的速度将很慢,因为要从第1个依次往后取,取出来后进行比较。平衡二叉树(构建平衡二叉树需要先排序,我们这里就不作考虑了)可以很好地解决这个问题,但二叉树的遍历(前序,中序,后序)效率要比数组低很多,原理如下图:

wKioL1Q1K23BgaUwAADpvekA47U748.jpg

代码如下:

package com.huawei.interview;

 

publicclass Node {

    publicintvalue;

    public Node left;

    public Node right;

   

    publicvoid store(int value)

    {

       if(value<this.value)

       {

           if(left == null)

           {

              left = new Node();

              left.value=value;

           }

           else

           {

              left.store(value);

           }

       }

       elseif(value>this.value)

       {

           if(right == null)

           {

              right = new Node();

              right.value=value;

           }

           else

           {

              right.store(value);

           }         

       }

    }

   

    publicboolean find(int value)

    {  

       System.out.println("happen" + this.value);

       if(value == this.value)

       {

           returntrue;

       }

       elseif(value>this.value)

       {

           if(right == null) returnfalse;

           returnright.find(value);

       }else

       {

           if(left == null) returnfalse;

           returnleft.find(value);

       }

 

    }

   

    public  void preList()

    {

       System.out.print(this.value + ",");

       if(left!=null) left.preList();

       if(right!=null) right.preList();

    }

   

    publicvoid middleList()

    {

       if(left!=null) left.preList();

       System.out.print(this.value + ",");

       if(right!=null) right.preList();      

    }

    publicvoid afterList()

    {

       if(left!=null) left.preList();

       if(right!=null) right.preList();

       System.out.print(this.value + ",");      

    }  

    publicstaticvoid main(String [] args)

    {

       int [] data = newint[20];

       for(int i=0;i<data.length;i++)

       {

           data[i] = (int)(Math.random()*100) + 1;

           System.out.print(data[i] + ",");

       }

       System.out.println();

      

       Node root = new Node();

       root.value = data[0];

       for(int i=1;i<data.length;i++)

       {

           root.store(data[i]);

       }

      

       root.find(data[19]);

      

       root.preList();

       System.out.println();

       root.middleList();

       System.out.println();      

       root.afterList();

    }

}

-----------------又一次临场写的代码---------------------------

import java.util.Arrays;

import java.util.Iterator;

 

public class Node {

    privateNode left;

    privateNode right;

    privateint value;

    //privateint num;

   

    publicNode(int value){

       this.value= value;

    }

    publicvoid add(int value){

      

       if(value> this.value)

       {

           if(right!= null)

              right.add(value);

           else

           {

              Nodenode = new Node(value);             

              right= node;

           }

       }

       else{

           if(left!= null)

              left.add(value);

           else

           {

              Nodenode = new Node(value);             

              left= node;

           }         

       }

    }

   

    publicboolean find(int value){

       if(value== this.value) return true;

       elseif(value > this.value){

           if(right== null) return false;

           elsereturn right.find(value);

       }else{

           if(left== null) return false;

           elsereturn left.find(value);         

       }

 

    }

   

    publicvoid display(){

       System.out.println(value);

       if(left!= null) left.display();

       if(right!= null) right.display();

      

    }

   

    /*publicIterator iterator(){

      

    }*/

   

    publicstatic void main(String[] args){

       int[]values = new int[8];

       for(inti=0;i<8;i++){

           intnum = (int)(Math.random() * 15);

           //System.out.println(num);

           //if(Arrays.binarySearch(values,num)<0)

           if(!contains(values,num))

              values[i]= num;

           else

              i--;

       }

      

       System.out.println(Arrays.toString(values));

      

       Noderoot  = new Node(values[0]);

       for(inti=1;i<values.length;i++){

           root.add(values[i]);

       }

      

       System.out.println(root.find(13));

      

       root.display();

      

    }

   

    publicstatic boolean contains(int [] arr, int value){

       inti = 0;

       for(;i<arr.length;i++){

           if(arr[i]== value) return true;

          

       }

       returnfalse;

    }

   

}

1、从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序:

1,张三,28

2,李四,35

3,张三,28

4,王五,35

5,张三,28

6,李四,35

7,赵六,28

8,田七,35

 

程序代码如下(答题要博得用人单位的喜欢,包名用该公司,面试前就提前查好该公司的网址,如果查不到,现场问也是可以的。还要加上实现思路的注释):

package com.huawei.interview;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.Comparator;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.TreeSet;

 

 

publicclass GetNameTest {

 

    /**

     *@paramargs

     */

    publicstaticvoid main(String[] args) {

       // TODO Auto-generatedmethod stub

       //InputStream ips =GetNameTest.class.getResourceAsStream("/com/huawei/interview/info.txt");

       //用上一行注释的代码和下一行的代码都可以,因为info.txtGetNameTest类在同一包下面,所以,可以用下面的相对路径形式

      

       Map results = new HashMap();

       InputStream ips = GetNameTest.class.getResourceAsStream("info.txt");

       BufferedReader in = new BufferedReader(new InputStreamReader(ips));

       String line = null;

       try {

           while((line=in.readLine())!=null)

           {

              dealLine(line,results);

           }

           sortResults(results);

       } catch (IOException e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

    }

   

    staticclass User

    {

       public  String name;

       public Integer value;

       public User(String name,Integer value)

        {

           this.name = name;

           this.value = value;

       }

 

       @Override

       publicboolean equals(Object obj) {

           // TODO Auto-generatedmethod stub

             

           //下面的代码没有执行,说明往treeset中增加数据时,不会使用到equals方法。

           boolean result = super.equals(obj);

           System.out.println(result);

           return result;

       }

    }

   

    privatestaticvoid sortResults(Map results) {

       // TODO Auto-generatedmethod stub

       TreeSet sortedResults = new TreeSet(

              new Comparator(){

                  publicint compare(Object o1, Object o2) {

                     // TODO Auto-generated methodstub

                     User user1 = (User)o1;

                     User user2 = (User)o2;

                     /*如果compareTo返回结果0,则认为两个对象相等,新的对象不会增加到集合中去

                      * 所以,不能直接用下面的代码,否则,那些个数相同的其他姓名就打印不出来。

                      * */

                    

                     //returnuser1.value-user2.value;

                     //returnuser1.value<user2.value?-1:user1.value==user2.value?0:1;

                     if(user1.value<user2.value)

                     {

                         return -1;

                     }elseif(user1.value>user2.value)

                     {

                         return 1;

                     }else

                     {

                         return user1.name.compareTo(user2.name);

                     }

                  }

                 

               }

       );

       Iterator iterator = results.keySet().iterator();

       while(iterator.hasNext())

       {

           String name = (String)iterator.next();

           Integer value = (Integer)results.get(name);

           if(value > 1)

           {            

              sortedResults.add(new User(name,value));            

           }

       }

      

       printResults(sortedResults);

    }

    privatestaticvoid printResults(TreeSet sortedResults)

    {

       Iterator iterator  =sortedResults.iterator();

       while(iterator.hasNext())

       {

           User user = (User)iterator.next();

           System.out.println(user.name + ":" + user.value);

       }  

    }

    publicstaticvoid dealLine(String line,Map map)

    {

       if(!"".equals(line.trim()))

       {

           String [] results = line.split(",");

           if(results.length == 3)

           {

              String name = results[1];

              Integer value = (Integer)map.get(name);

              if(value == null) value = 0;

              map.put(name,value + 1);

           }

       }

    }

 

}



你可能感兴趣的:(Java基础部分9)