您可以使用递归方法和 Exception 处理机制来检测路径是否不存在 .
public void insertpath(int val, String path) throws Exception {
if(path == null || path.equals("")) {
throw new Exception("Path is not effective or an empty string.");
}
Node node = new Node(val,null,null);
if(path.equals("X")) {
if(this.root != null) {
throw new Exception("BSTree is not correct.");
} else {
this.root = n;
}
} else {
root=path(root,path,0,node);
}
}
private void insertpath (Node current, String path, int index, Node node) throws Exception {
if(current == null) {
throw new Exception("Illegal path.");
}
char ci = path.charAt(index);
index++;
if(index < path.length()) {
//we're not at the end of the path yet
switch(ci) {
case 'L' :
insertpath(current.left,path,index,node);
break;
case 'R' :
insertpath(current.right,path,index,node);
break;
default :
throw new Exception("Invalid path character '"+ci+"'.");
break;
}
} else {
switch(ci) {
case 'L' :
if(this.left != null) {
throw new Exception("BSTree is not correct.");
} else {
current.left = node;
}
break;
case 'R' :
if(this.right != null) {
throw new Exception("BSTree is not correct.");
} else {
current.right = node;
}
break;
default :
throw new Exception("Invalid path character '"+ci+"'.");
break;
}
}
}
它可以抛出几个带有几条消息的 Exception :
"BSTree is not correct." 如果要在已使用的路径上插入节点;
如果您的路径包含一个没有语义含义的奇怪字符,则
"Invalid path character 'a'." (或与 a 不同的内容);
"Illegal path." 如果路径无法使用,例如 RR 示例;和
"Path is not effective or an empty string." 如果路径无效( null )或为空( "" ) .
显然,您可以发明其他 Exception ,以便程序可以更容易地区分不同的问题 .