首页 > 解决方案 > 如何在控制台中打印通用树?

问题描述

我一直在尝试使用Node下面的此类在控制台中打印出格式正确的通用树。我通常会展示我的尝试,但我什至不知道从哪里开始。任何人都可以给我一些关于如何解决这个问题的指示吗?

class Node{
  public String letter;
  public Node parent;
  public Map<String, Node> connections = new LinkedHashMap<String, Node>();
  
  public Node(String letter, Node parent){ 
     this.letter = letter; 
     this.parent = parent; 
  }
  
  public int getChildrenCount(){ return connections.size(); }
  
  public ArrayList<Node> getChildren(){
     ArrayList<Node> out = new ArrayList<Node>();
     for(Node node : connections.values()){
        out.add(node);
     }
     return out;
  }
  
  public String toString(){ return letter; }
}  

我希望输出看起来像这样,例如:

 |--j
 |
 |  |--c
 a--b
 |  |--d
 |
 |     |--g
 |  |--f 
 |--e
    |--h
       |--i

标签: javatree

解决方案


您尝试做的事情是可能的,但很难智能地实现,因为它需要做出间距决定以避免重叠。解密树的一个简单的解决方案是:

public String toString() { 
 String s = letter + "(";
 for (Node n : connections.keySet()) {
  s += n.toString() + ",";
 }
 return s + ")";
}

如果你需要它格式化你如何显示(编辑):

HashMap<String, ArrayList<String>> map;

public String toString() { 
 findAsString();
 ArrayList<String> lines = map.get(this.letter);
 for (String l : lines) {
  System.out.println(l); 
 }
}

public String findAsString() { 
 map = new HashMap<>(); 
 for (Node n : connections.keySet()) {
  findAsString(n); 
 }
 ArrayList<String> lines = new ArrayList<>(); 
 for (Node n : connections.keySet()) {
  ArrayList<String> nodeLines = map.get(n.letter);
  for (String s : nodeLines) {
   // CONFIGURE THIS PREFIX to include the letter itself, and needed lines
   String prefix = "|  "; 
   lines.add(prefix + s); 
  }
  lines.add("");
 }
 if (nodeLines.size() == 0) {
  lines.add("|--" + this.letter); 
 }
 map.put(this.letter, lines);
}

推荐阅读