
java如何递归返回树结构的查询结果?
问题详情:
需要实现根据给定名称(如“秦朗”)查询一个树形数据结构并返回结果,其中结果以一条链路表示,如“三国-曹操-秦朗”。
代码:
立即学习“Java免费学习笔记(深入)”;
public class people {
private list<people> 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<people> query(people people, string name) {
list<people> 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<PeopleVO> 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<PeopleVO> searchResult = searchPeople(tree, "孙坚");
List<PeopleVO> 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<PeopleVO> createTree(List<PeopleVO> lists, int pid) {
// ... implementation omitted
}
// Search for a person in the tree structure
private static List<PeopleVO> searchPeople(List<PeopleVO> tree, String name) {
// ... implementation omitted
}
// Assemble the result nodes into a tree structure
private static List<PeopleVO> createTree2(List<PeopleVO> nodeList) {
// ... implementation omitted
}
}优势:
以上就是Java递归查询树结构:如何返回包含完整路径的树形查询结果?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号