Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将特定路径打印到二叉树中的节点_Java_Binary Tree_Binary Search Tree_Traversal_Preorder - Fatal编程技术网

Java 将特定路径打印到二叉树中的节点

Java 将特定路径打印到二叉树中的节点,java,binary-tree,binary-search-tree,traversal,preorder,Java,Binary Tree,Binary Search Tree,Traversal,Preorder,我试图使用预排序遍历在由字符a-z和a-z组成的二叉树中找到一个节点,其中向左标记为0,向右标记为1,因此对于向左有两个分支的节点,正确的输出看起来像00。节点未排序 到目前为止,我有: static String routeNum = ""; private static String onePath(BinaryNodeInterface<Character> root, String route) { BinaryNodeInterface<Cha

我试图使用预排序遍历在由字符a-z和a-z组成的二叉树中找到一个节点,其中向左标记为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);

要打印路由字符串。

请在不使用静态字符串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;

我试过了,但它会为每个节点打印出一条路径。我有另一个方法应该这样做,这就是我复制这个方法的地方;然后调用System.out.printlntoPrint;您需要调用System.out.println,否则将不会有任何输出。routeNum=route+0;onePathtemp.getLeftChild,路由+0;routeNum=路由+1;onePathtemp.getRightChild,路由+1;。一个干净的方法是使用StringBuffer
String path = onePath(root, "");
Print(path);