如何从二叉树中打印元素而忽略所有重复元素? [英] How to print elements from a binary tree ignoring all the repeating ones?

查看:85
本文介绍了如何从二叉树中打印元素而忽略所有重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 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.

例如,文件如下:

aaa 
zzz
the the the the 

,输出应如下所示:

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.

推荐答案

您可以使用HashMap存储成对的<String, List>,其中String是您的密钥,而List是职位列表,找到了这样的密钥.如果您需要检查地图中是否已经有钥匙,请执行

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);

这篇关于如何从二叉树中打印元素而忽略所有重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆