
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;}
问题:
Reclaim.ai
为优先事项创建完美的时间表
90 查看详情
上述代码会返回该名称的所有匹配项,但不会构建包含所有父节点的树结构。
解决方案:
要构建包含所有父节点的树,可以使用以下优化后的代码:
import com.alibaba.fastjson2.JSON;import lombok.Data;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;@Datapublic 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格式。优化了代码以提高性能。
以上就是Java递归查询树结构:如何返回包含完整路径的树形查询结果?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/997624.html
微信扫一扫
支付宝扫一扫