java 生成樹形結構


package com.stu;
 
import java.util.ArrayList;
import java.util.List;
 
public class TreeUtils {
 
    //把一個List轉成樹
    static List<Node> buidTree(List<Node> list){
        List<Node> tree=new ArrayList<>();
        for(Node node:list){
            if(node.getPid() == 0){
                tree.add(findChild(node,list));
            }
        }
        return tree;
    }
 
    static Node findChild(Node node, List<Node> list){
        for(Node n:list){
            if(n.getPid() == node.getId()){
                if(node.getChildren() == null){
                    node.setChildren(new ArrayList<Node>());
                }
                node.getChildren().add(findChild(n,list));
            }
        }
        return node;
    }
 
    public static void main(String[] args) {
        Node node1=new Node(1,"山東省",0);
        Node node2=new Node(2,"德州市",1);
        Node node3=new Node(3,"夏津縣",2);
        Node node4=new Node(4,"濟南市",1);
        Node node5=new Node(5,"天津",0);
        Node node6=new Node(6,"紅橋區",5);
        List<Node> list=new ArrayList<>();
        list.add(node1);
        list.add(node2);
        list.add(node3);
        list.add(node4);
        list.add(node5);
        list.add(node6);
        List<Node> nodes = buidTree(list);
        System.out.println(nodes);
    }
}
 ```


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM