I want to traverse a binary tree from right to left and add to a queue every item with same last name. I have correctly implement a Queue List class and a Tree Node class but, i get a null pointer exception when i try to find something. (Of course i have written an insertion method for the binary tree).
public class ST {
private TreeNode root;
private int size;
private Queue q;
public Queue searchByLastName(String last_name) {
searchByLastNameRec(this.root, last_name);
return q;
}
private void searchByLastNameRec(TreeNode newroot, String last_name) {
if (newroot == null)
return;
if (newroot.right != null) {
if (newroot.right.item.getLast_name().equalsIgnoreCase(last_name)) {
q.put(newroot.right.item);
}
searchByLastNameRec(newroot.right, last_name);
}
if (newroot.left != null) {
if (newroot.left.item.getLast_name().equalsIgnoreCase(last_name)) {
q.put(newroot.left.item);
}
searchByLastNameRec(newroot.left, last_name);
}
}
public class TreeNode {
Suspect item;
TreeNode left, right, parent;
int N;
public TreeNode(Suspect item) {
if (item == null)
throw new IllegalArgumentException();
this.item = item;
}
}
解决方案
Try this
private void searchByLastNameRec(TreeNode newroot, String last_name) {
if (newroot == null || newroot.item == null)
return;
if (Objects.equals(last_name, newroot.item.getLast_name()))
q.put(newroot.item);
searchByLastNameRec(newroot.right, last_name);
searchByLastNameRec(newroot.left, last_name);
}