Java实现树(数据结构)工具类

一、树数据结构概念

树是一种抽象数据类型(ADT)或是实现这种抽象数据类型的数据结构,用来模拟具有树状结构性质的数据集合。它是由n(n>0)个有限节点组成一个具有层次关系的集合。把它叫做“树”是因为它看起来像一棵倒挂的树,也就是说它是根朝上,而叶朝下的,具有以下特点:

  • 每个节点有零个或多个子节点;
  • 没有父节点的节点称为根节点;
  • 每一个非根节点有且只有一个父节点;
  • 除了根节点外,每个子节点可以分为多个不相交的子树;

二、Java示例(树状结构解析)

1.工具类

package com.tzt.util;

import com.tzt.entity.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * Tree解析工具类
 * @author libb
 * @version 1.0
 */
public class TreeUtil {

    private List treeNodeList =new ArrayList<>();

    public TreeUtil(List list){
        treeNodeList = list;
    }

    /**
     * 获取节点信息
     * @param nodeId 节点ID
     * @return
     */
    public TreeNode getNodeById(int nodeId){
        TreeNode treeNode = new TreeNode();
        for (TreeNode item : treeNodeList) {
            if (item.getId() == nodeId) {
                treeNode = item;
                break;
            }
        }
        return treeNode;
    }

    /**
     * 获取子节点信息
     * @param nodeId 节点ID
     * @return
     */
    public List getChildrenNodeById(int nodeId){
        List childrenTreeNode = new ArrayList();
        for (TreeNode item : treeNodeList) {
            if(item.getParentId() == nodeId){
                childrenTreeNode.add(item);
            }
        }
        return childrenTreeNode;
    }

    /**
     * 递归生成Tree结构数据
     * @param rootId 根节点ID
     * @return
     */
    public TreeNode generateTreeNode(int rootId){
        TreeNode root = this.getNodeById(rootId);
        List childrenTreeNode = this.getChildrenNodeById(rootId);
        for (TreeNode item : childrenTreeNode) {
            TreeNode node = this.generateTreeNode(item.getId());
            root.getChildrenList().add(node);
        }
        return root;
    }

    public static void main(String[] args) {
        List nodeList = new ArrayList<>();
        TreeNode treeNode = new TreeNode();
        treeNode.setId(1);
        treeNode.setName("中国");
        treeNode.setParentId(0);
        nodeList.add(treeNode);
        treeNode = new TreeNode();
        treeNode.setId(2);
        treeNode.setName("北京市");
        treeNode.setParentId(1);
        nodeList.add(treeNode);
        treeNode = new TreeNode();
        treeNode.setId(3);
        treeNode.setName("浙江省");
        treeNode.setParentId(1);
        nodeList.add(treeNode);
        treeNode = new TreeNode();
        treeNode.setId(4);
        treeNode.setName("杭州市");
        treeNode.setParentId(3);
        nodeList.add(treeNode);
        treeNode = new TreeNode();
        treeNode.setId(5);
        treeNode.setName("西湖区");
        treeNode.setParentId(4);
        nodeList.add(treeNode);
        treeNode = new TreeNode();
        treeNode.setId(6);
        treeNode.setName("滨江区");
        treeNode.setParentId(4);
        nodeList.add(treeNode);
        treeNode = new TreeNode();
        treeNode.setId(7);
        treeNode.setName("金华市");
        treeNode.setParentId(3);
        nodeList.add(treeNode);
        TreeUtil treeUtil = new TreeUtil(nodeList);
        treeNode = treeUtil.generateTreeNode(1);
        System.out.println("树状结构Json格式数据:" + JsonUtils.objectToJson(treeNode, 1));
    }
}

2.辅助类

package com.tzt.entity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by libb on 2018/11/6.
 */
public class TreeNode {

    /**
     * 节点ID
     */
    private Integer id;

    /**
     * 节点名称
     */
    private String name;

    /**
     * 父节点ID
     */
    private Integer parentId;

    /**
     * 子节点列表
     */
    private List childrenList = new ArrayList();

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id=id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name=name;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId=parentId;
    }

    public List getChildrenList() {
        return childrenList;
    }

    public void setChildrenList(List childrenList) {
        this.childrenList=childrenList;
    }
}

3.Java对象与Json格式数据转换类

package com.tzt.util;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created by libb on 2018/11/6.
 */
public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串
     * @param obj 需转换的对象
     * @param  flag Json格式化标识(0-否,1-是)
     * @return
     */
    public static  String objectToJson(T obj, int flag) {
        if (obj == null) {
            return null;
        }
        try {
            String string;
            if (flag == 1) {
                string = obj instanceof String ? (String) obj : MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            } else {
                string = obj instanceof String ? (String) obj : MAPPER.writeValueAsString(obj);
            }
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json结果集转化为对象
     *
     * @param jsonData json数据
     * @param beanType 对象中的object类型
     * @return
     */
    public static  T jsonToPojo(String jsonData, Class beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json数据转换成pojo对象list
     * 

Title: jsonToList

*

Description:

* @param jsonData * @param beanType * @return */ public static List jsonToList(String jsonData, Class beanType) { JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); try { List list = MAPPER.readValue(jsonData, javaType); return list; } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { System.out.println("测试字符串对象:" + objectToJson("hello world", 1)); } }

总结

树状数据结构在生活及程序随处可见,作为程序开发必须熟练掌握其原理。
参考文献:https://zh.wikipedia.org/wiki/树_(数据结构)

你可能感兴趣的:(数据结构)