深度优先搜索最大深度:
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);
}
}
我的笔记博客版权
我的笔记博客版权