【发布时间】:2019-11-12 21:56:55
【问题描述】:
这就是我要插入到我的树中的内容:
我正在搜索:Node nd = searchNodeIterativly(root, "Ortiz");
我得到一个空指针错误。
由于"Ortiz" 实际上在树中,我不明白为什么我的循环中的返回不起作用。
是算法,还是我忽略了什么?
这是我的代码:
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);
}
}
}
【问题讨论】:
-
能否展示一下Node类的结构,尤其是方法compareTo和方法insert?
-
“Ortiz”不等于
"Ortiz "。 (空格) -
我刚改了,我以为就这样了,可惜还是没有。
-
我认为你走错路了。您必须将根作为属性添加到二叉树类。我做了一个方法来显示你树中的所有节点,它给了我 java.lang.StackOverflowError。
标签: java tree binary-search-tree