【问题标题】:Printing specific path to a node in a binary tree打印二叉树中节点的特定路径
【发布时间】:2014-11-22 02:15:26
【问题描述】:

我正在尝试使用前序遍历在由字符 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() 否则不会有任何输出。
  • routeNum = route + "0"; onePath(temp.getLeftChild(),route+"0");routeNum = route + "1"; onePath(temp.getRightChild(), route+"1");。干净的方法是使用 StringBuffer

标签: java binary-tree binary-search-tree traversal preorder


【解决方案1】:

试试这个不带静态字符串 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);

【讨论】:

    【解决方案2】:

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

    System.out.println(route);
    

    打印出路由字符串。

    【讨论】:

    • 我试过了,但它会打印出每个节点的路径。我有另一种方法可以做到这一点,这就是我复制这个方法的地方。
    • 执行类似 String toPrint = onePath(root, "");然后调用 System.out.println(toPrint);
    猜你喜欢
    • 2012-04-15
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多