简体   繁体   中英

Search by inorder in binary search tree

I use inorder to show result of search name which store in binary search tree but when i run it example i have: Employee name "abc" and "ab" and i input name ="abc" it show 2 of them.Anyone can help me what is my fault :( ty

public void searchFull(String name) {
        EmployeeSLLNode p = root;
        n=0;
        if (p != null) {
            inorder(p.left);
            if(p.info.getFullname().equals(name)) {
                    n++;
             System.out.printf("%2s  %-5s   %-8s   %-6s   %-6s%n", n, p.info.getID(), p.info.getFullname(), p.info.getAge(), p.info.getGender());
            }
             inorder(p.right);
        }
    }

In-order traversal is equivalent to iterating a TreeMap 's entrySet .

final Map<String, Employee> employees = new TreeMap<String, Employee>();
...
for (final Map.Entry<String, Employee> entry : employees.entrySet()) {
  /* iterating in-order */
}

TreeMap simply uses a binary search tree (in particular, according to the specification , a red-black tree). Consider using it instead of rolling your own solution ;-)


That being said, if you're intent on rolling your own, maybe try something like this...

public EmployeeSSLnode search(final EmployeeSSLnode root, final String name) {
  EmployeeSSLnode left;
  return root == null
    ? null
    : (left = search(root.left, name)) == null
      ? root.info.getFullname().equals(name)
        ? root
        : search(root.right, name)
      : left;
}

I think this is what you can do.But ensure that your your tree doesn't have the duplicate names.

public void searchFull(EmployeeSLLnode p, String name) {
    if (p == null)
        return;
    searchFull(p -> left, name);
    if (p.info.getFullname().equals(name)) {
        //This is the node do other stuff here
        return;
    }
    searchFull(p -> right, name);

}

Also it would be better to do general search in BST instead of searching through Inorder. Inorder searcing in BST would actually ruin the whole purpose of BST . Compare the input Name with node using compareTo() method of String class and depending on whether name is alphabetically later or earlier move either to right or left.

Most of this code should be inside the inorder() method. Undoubtedly it actually is, so you have two prints, so you get two outputs. All the searchFull() method should do is call inorder(root).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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