首页 > 解决方案 > 将树(非二进制)转换为路径列表

问题描述

我有一个树实现:

class Node {
    String name;
    List<Node> childs;
}

我需要将它转换为从根到每个叶子的路径列表。

标签: javaalgorithm

解决方案


我没有机会测试这段代码,但总体思路是通过子元素的 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);
        }
    }
}


推荐阅读