How to print elements from a binary tree ignoring all the repeating ones?

一笑奈何 提交于 2020-01-25 11:53:09

问题


 public void printTree(node root)
    {
        if(root != null)
        {
            printTree(root.left);
            System.out.print(root.word + " " + root.line+" ");
            String tempStr=root.word; int tempLn=root.line; //don't know how to use it
            printTree(root.right);
        }
    }

Assume that the tree is already sorted in a lexicographic order.

For example, the file is like this:

aaa 
zzz
the the the the 

and the output should be like this:

aaa line: 1
the line: 3 3 3 3
zzz line: 2

My code now displays the same words for many times. I don't know how to organize this chunk of code.


回答1:


The problem is that you are instantly outputting information as you find it. Instead, you need to store the data you come across in a continual fashion.

You will probably want to use a HashMap<String, List<Integer>> data structure to hold this information.




回答2:


You can use a HashMap to store pairs of <String, List>, where String will be your key and List will be a list of positions, where such key was found. If you need to check, if a key is already in the map, you do

map.contains(key);

and if there is one, you can update the appropriate list by doing

map.get(key).add(page);


来源:https://stackoverflow.com/questions/21841283/how-to-print-elements-from-a-binary-tree-ignoring-all-the-repeating-ones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!