问题详情:
需要实现根据给定名称(如“秦朗”)查询一个树形数据结构并返回结果,其中结果以一条链路表示,如“三国-曹操-秦朗”。
代码:
立即学习“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 } }
优势:
- 创建了一个包含所有父节点的树结构。
- 使用了fastjson库将树结构转换为json格式。
- 优化了代码以提高性能。