×

五分钟学会找树结构的最大深度和所有路径

我的笔记 我的笔记 发表于2022-05-09 10:37:13 浏览1876 评论0

抢沙发发表评论

深度优先搜索最大深度:

    public int maxDepth(Node root) {
        if (root == null) {
            return 0;
        }
        int maxChildDepth = 0;
        List<Node> children = root.children;
        for (Node child : children) {
            int childDepth = maxDepth(child);
            maxChildDepth = Math.max(maxChildDepth, childDepth);
        }
        return maxChildDepth + 1;
    }

求出所有路径:

public static void findAllPaths(TreeNode treeNodes, String path, List<String>paths) {
    path += treeNodes.getLabel() + "->";
    if (treeNodes == null || CollUtil.isEmpty(treeNodes.getChild())) {
        String leafPath = path;
        paths.add(leafPath);
        return;
    }
    for (int i = 0, len = treeNodes.getChild().size(); i < len; i++) {
        findAllPaths(treeNodes.getChild().get(i), path);
    }
}


我的笔记博客版权我的笔记博客版权