0

我正在尝试使用前序遍历在由字符 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;
}

输出表明我正在到达正确的节点,但它不打印路径。

4

2 回答 2

0

在没有静态 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);
于 2014-11-22T02:35:11.970 回答
-1

您永远不会调用 print 方法。您可以使用:

System.out.println(route);

打印出路线字符串。

于 2014-11-22T02:28:02.057 回答