This is what I'm inserting into my tree:
I'm searching for: Node nd = searchNodeIterativly(root, "Ortiz");
and I'm getting a null pointer error.
Since "Ortiz"
is actually in the tree, I don't see why my return in the loop isn't working.
Is it the algorithm, or something I'm overlooking?
Here's my code:
import java.io.IOException;
import java.util.*;
public class BinaryTree {
public static class Node {
String name, number;
Node Llink, Rlink;
boolean Ltag, Rtag;
Node(String name, String number) {
this.name = name;
this.number = number;
Llink = null;
Rlink = null;
}
}
public static Node insert(Node node, String name, String num) {
// Searching for a Node with given value
Node Q = node;
Node P = null; // Parent of key to be inserted
while (Q != null) {
// If key already exists, return
if (name == (Q.name)) {
System.out.printf("Duplicate Key !\n");
return node;
}
P = Q;
if (name.compareTo(Q.name) < 0) {
if (Q.Ltag == false)
Q = Q.Llink;
else
break;
} else {
if (Q.Rtag == false)
Q = Q.Rlink;
else
break;
}
}
Node tmp = new Node(name, num);
tmp.name = name;
tmp.Ltag = true;
tmp.Rtag = true;
if (P == null) {
node = tmp;
tmp.Llink = null;
tmp.Rlink = null;
} else if (name.compareTo(P.name) < 0) {
tmp.Llink = P.Llink;
tmp.Rlink = P;
P.Ltag = false;
P.Llink = tmp;
} else {
tmp.Llink = P;
tmp.Rlink = P.Rlink;
P.Rtag = false;
P.Rlink = tmp;
}
return node;
}
public static Node searchNodeIterativly(Node node, String name) {
while (node != null) {
if (name.compareTo(node.name) > 0) {
node = node.Llink;
} else if (name.compareTo(node.name) < 0) {
node = node.Rlink;
} else {
return node;
}
}
return node;
}
public static void main(String[] args) throws IOException {
// BinaryTree tree = new BinaryTree();
Node root = new Node("Moutafis ", "295-1492");
insert(root, "Ikerd ", "291-1864");
insert(root, "Gladwin ", "295-1601");
insert(root, "Robson ", "293-6122");
insert(root, "Dang ", "295-1882");
insert(root, "Bird ", "291-7890");
insert(root, "Harris ", "294-8075");
insert(root, "Ortiz ", "584-3622");
Node nd = searchNodeIterativly(root, "Ortiz ");
if (nd == null) {
System.out.println("no result found!");
} else {
System.out.println(nd.name + ": " + nd.number);
}
}
}