打印二进制树中节点的特定路径
问题描述:
我试图使用预序遍历来查找由字符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;
}
输出表明我正在向正确的节点,但是它不打印的路径。
答
你永远不会调用打印方法。您可以使用:
System.out.println(route);
打印出路由字符串。
+0
我试过,但它打印出每个节点的路径。我有另一种方法应该做到这一点,这是我从中复制这种方法。 – 2014-11-22 02:31:35
+0
做一些像String toPrint = onePath(root,“”);然后调用System.out.println(toPrint); – holtc 2014-11-22 02:33:07
答
试试这个没有静态字符串的代码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()或有_won't_有任何输出。 – splrs 2014-11-22 02:40:24
'routeNum = route +“0”; onePath(temp.getLeftChild(),route +“0”);' 'routeNum = route +“1”; \t onePath(temp.getRightChild(),route +“1”);'。干净的方式来做到这一点是使用StringBuffer – arunmoezhi 2014-11-22 02:41:35