java - 将树(非二进制)转换为路径列表
问题描述
我有一个树实现:
class Node {
String name;
List<Node> childs;
}
我需要将它转换为从根到每个叶子的路径列表。
解决方案
我没有机会测试这段代码,但总体思路是通过子元素的 for-each 循环遍历树。我们通过在每个递归步骤中添加当前名称来将当前路径保存在字符串中。然后在点击叶子时,我们将当前路径添加到列表中。
public ArrayList<String> buildListOfPaths(Node tree) {
ArrayList<String> list = new ArrayList<String>();
String str = "";
traverse(tree, list, str);
return list;
}
// The idea on how to iterate the elements comes from:
// https://stackoverflow.com/a/19338057
public void traverse(Node root, ArrayList<String> list, String str){
// we know it's a leaf so we can add this path to the list
if (root.getChildren() == null) {
list.add(str + root.name);
return;
} else {
for(Node each : root.getChildren()){
traverse(each, list, str + each.name);
}
}
}
推荐阅读
- python - python中的有序排列
- python - 运行此程序时,我不断收到此错误。我已经尝试了我能想到的一切,但仍然无法正常工作
- django - Django ORM在没有模型形式的情况下保存上传的文件
- postgresql - 在 PostgreSQL 列中存储特殊(拼音字母)字符
- asp.net-core-3.1 - 如何从 .net core 3.1 api 响应中删除“服务器”标头?
- verilog - 数组声明区别verilog
- ios - 将DAO层(领域或核心数据)作为多线程应用程序的单例是否可以?
- laravel - 使用 ShouldQueue 通知电子邮件序列化错误与缺少请求对象错误
- oauth-2.0 - Ejabberd 18.12.1 - X-OAUTH2 因令牌无效而失败 - 如何设置?
- laravel - 如何在 Godaddy 主机上托管 laravel 网站