简体   繁体   English

如何获得Java二进制搜索树中的每个项目并将其与另一个变量进行比较?

[英]How would I get each item in a java binary search tree and compare it to another variable?

I wrote code for a linked list dvd inventory program that allows me to traverse the list using a for loop and compare each dvd title on the list to the dvd title that was entered by the user. 我为一个链接列表DVD库存程序编写了代码,该程序使我可以使用for循环遍历列表,并将列表上的每个DVD标题与用户输入的DVD标题进行比较。 If the title matched, it would then print out the number of copies that are in stock of that title. 如果标题匹配,则将打印出该标题库存的份数。 The code for this is below: 此代码如下:

movieToCommand = input.substring(2, input.length()).toLowerCase();

for (int i = 1; i <= movies.length(); i++) {
  if (movies.get(i).getTitle().equals(inputMovie)) {
    System.out.println("There are currently " 
     + movies.get(i).getCopies()
     + " copies of \"" 
     + movies.get(i).getTitle()
     + "\" in stock.");
    }
  }

I am now re-writing the project using a binary search tree. 我现在使用二进制搜索树重写项目。 I have gotten the tree to be able to add items, however I cannot figure out how to access each item on the tree and compare it like I did for the linked list. 我已经有了可以添加项目的树,但是我无法弄清楚如何访问树上的每个项目并像对链表那样进行比较。 Does anyone know how I can do this? 有人知道我该怎么做吗?

Thanks 谢谢

Since you have a binary search tree, and the user is simply entering a movie title, I am assuming that your tree is built based on String . 由于您有一个二进制搜索树,并且用户只是输入电影标题,因此我假设您的树是基于String构建的。 You can keep the movie titles in a TreeMap . 您可以将电影标题保留在TreeMap A TreeMap is implemented using a Red-Black tree, which is a self-balancing binary search tree. TreeMap是使用Red-Black树实现的,Red-Black树是自平衡的二进制搜索树。

Maintain a TreeMap (say, allMovies ) with movie titles as keys and the actual movie object (on which you are calling getCopies() ) as values. 维护一个TreeMap(例如allMovies ),以电影标题作为键,并以实际电影对象(您在其上调用getCopies() )作为值。 Therefore, once the user gives a String object (a movie title, say, String aTitle; ), you will simply need to return allMovies.get(aTitle).getCopies() . 因此,一旦用户提供String对象(电影标题,例如String aTitle; ),您只需要返回allMovies.get(aTitle).getCopies()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM