Parent-child tree structure data query

Databases generally provide data query function tree structure, but may require additional configuration, occasionally because design errors can lead to write queries like shit uncomfortable, the amount of data in the case, simply check in Full code combination

import java.util.*;

/**
 * @author css
 * @data 2019/6/24 10:33
 */
public class Test<T> {
    private List<Node<T>> list = new ArrayList<>();

    public class Node<T> {
        Object id;
        Object pid;
        String name;
        T t;

        Node<T> parent;
        LinkedList<Node<T>> children = new LinkedList<>();

        @Override
        public String toString() {
            return "Node{" +
                    "id=" + id +
                    ", pid=" + pid +
                    ", name=" + name +
                    ", t=" + t +
                    ", children=" + children +
                    '}';
        }
    }

    public void add(Object id, Object pid, String name, T t) {
        Node<T> node = new Node<>();
        node.id = id;
        node.pid = pid;
        node.name = name;
        node.t = t;
        list.add(node);
    }

    public Node<T> toTree(Object root) {
        for (Node<T> i : list) {
            for (Node<T> j : list) {
                if (i.id.equals(j.pid)) {
                    i.children.add(j);
                    j.parent = i;
                }
            }
        }
        for (Node<T> i : list) {
            if (root.equals(i.id)) {
                return i;
            }
        }
        return null;
    }

    public List<T> getParent(Node<T> node) {
        Node<T> p = node.parent;
        if (p == null) {
            return null;
        } else {
            List<T> list = new ArrayList<>();
            while (p != null) {
                list.add(p.t);
                p = p.parent;
            }
            return list;
        }
    }

    public List<T> getChildren(Node<T> node) {
        LinkedList<Node<T>> c = new LinkedList<>(node.children);
        if (c.isEmpty()) {
            return null;
        } else {
            List<T> list = new ArrayList<>(c.size());
            Node<T> e;
            while (!c.isEmpty()) {
                e = c.pollFirst();
                list.add(e.t);
                if (!e.children.isEmpty()) {
                    c.addAll(e.children);
                }
            }
            return list;
        }
    }

    public static void main(String[] args) {
        Test<String> t = new Test<>();
        t.add(1, null, "1000", "node1");
        t.add(2, 1, "1001", "node2");
        t.add(3, 2, "1002", "node3");
        t.add(4, 2, "1003", "node4");
        Test.Node n = t.toTree(1);
        System.out.println(t.getChildren(n));
    }
}

 

Guess you like

Origin www.cnblogs.com/chenss15060100790/p/11122154.html