[英]Printing specific path to a node in a binary tree
我正在尝试使用顺序遍历在由字符az和AZ组成的二叉树中找到一个节点,其中向左标记为“ 0”,向右标记为“ 1”,以便正确对于左边两个分支的节点,输出看起来像“ 00”。 节点未排序。
到目前为止,我有这个:
static String routeNum = "";
private static String onePath(BinaryNodeInterface<Character> root, String route) {
BinaryNodeInterface<Character> temp = root;
if(temp != null){
if(temp.hasLeftChild()){
routeNum = onePath(temp.getLeftChild(),route+"0");
}
if(temp.hasRightChild()){
routeNum = onePath(temp.getRightChild(), route+"1");
}
}
System.out.print(route);
return route;
}
输出表明我正在到达正确的节点,但未显示路径。
在没有静态String routeNum =“”的情况下尝试此代码;
private static String onePath(BinaryNodeInterface<Character> root, String route) {
BinaryNodeInterface<Character> temp = root;
if(temp != null){
if(temp.hasLeftChild()){
route += "0";
onePath(temp.getLeftChild(),route);
}
if(temp.hasRightChild()){
route += "1";
onePath(temp.getRightChild(), route);
}
}
system.out.println(route);
return route;
}
调用此函数
String path = onePath(root, "");
Print(path);
您永远不会调用打印方法。 您可以使用:
System.out.println(route);
打印出路线字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.