
java如何递归返回树结构的查询结果?
问题详情:
需要实现根据给定名称(如“秦朗”)查询一个树形数据结构并返回结果,其中结果以一条链路表示,如“三国-曹操-秦朗”。
代码:
立即学习“Java免费学习笔记(深入)”;
public class people {
private list children;
private string name;
// ... getter and setter methods omitted
}
public static void main(string[] args) {
// ... code to create and populate the tree structure
}
public static list query(people people, string name) {
list result = new arraylist<>();
// check if the current node matches the name
if(people.getname().contains(name)) {
return arrays.aslist(people);
} else {
// if not, recurse into the children
if(people.getchildren() != null) {
for (people p : people.getchildren()) {
result.addall(query(p, name));
}
}
}
return result;
} 问题:
上述代码会返回该名称的所有匹配项,但不会构建包含所有父节点的树结构。
解决方案:
要构建包含所有父节点的树,可以使用以下优化后的代码:
import com.alibaba.fastjson2.JSON;
import lombok.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Data
public class PeopleVO {
private Integer id;
private String peopleName;
private Integer parentId;
List children = new ArrayList<>();
// ... other methods omitted
// Main method
public static void main(String[] args) {
// ... code to create and populate the tree structure
// Search for "孙坚" and return the results as a tree
List searchResult = searchPeople(tree, "孙坚");
List resultTree = createTree2(searchResult);
System.out.println(JSON.toJSONString(resultTree));
// Expected output: [{"children":[{"id":3,"parentId":0,"peopleName":"孙坚"}],"id":0,"parentId":-1,"peopleName":"三国"}]
}
// Create a tree structure from a list of nodes
private static List createTree(List lists, int pid) {
// ... implementation omitted
}
// Search for a person in the tree structure
private static List searchPeople(List tree, String name) {
// ... implementation omitted
}
// Assemble the result nodes into a tree structure
private static List createTree2(List nodeList) {
// ... implementation omitted
}
} 优势:
- 创建了一个包含所有父节点的树结构。
- 使用了fastjson库将树结构转换为json格式。
- 优化了代码以提高性能。










