java 树形_JAVA树形数据结构的实现

package testng;

import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;

import org.codehaus.jackson.map.JsonMappingException;

public class Test {

/**

* 添加节点

* @param nodeMap

* @param parentNodeName 父节点名称

* @param nodeName

*/

public static void addNode(Map nodeMap,String parentNodeName,String nodeName){

Node parentNode = null != parentNodeName ? nodeMap.get(parentNodeName) : null;

Node node = nodeMap.get(nodeName);

if(null != node){

return;

}

node = new Node();

node.setName(nodeName);

nodeMap.put(nodeName, node);

if(null != parentNode){

parentNode.addChild(node);

node.setParent(parentNode);

}

}

public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {

String [] arrays = new String[]{

"测试/测试1/测试2",

"工单/问题反馈309",

"工单/问题反馈565",

"工单/问题反馈54",

"工单/问题反馈310",

"测试专用/123456/test/123"

};

Map resultMap = new HashMap();

for(String line : arrays){

String nodeNameArray [] = line.split("/");

String preNodeName = null;

for(String curNodeName : nodeNameArray){

addNode(resultMap,preNodeName,curNodeName);

preNodeName = curNodeName;

}

}

for(Map.Entry entry : resultMap.entrySet()){

Node node = entry.getValue();

if(null == node.getParent()){

print(node,"");

}

}

}

/**

* 递归打印node

* @param node

* @param blank

*/

public static void print(Node node,String blank){

System.out.println(blank + node.getName());

if(node.getChilds() == null || node.getChilds().isEmpty()){

return;

}

for(Node cur : node.getChilds()){

print(cur,blank + " ");

}

}

static class Node{

private String name;

private int index;

private List childs;

private Node parent;

public List getChilds() {

return childs;

}

public void addChild(Node child) {

if(null == childs){

childs = new ArrayList();

}

childs.add(child);

}

public Node getParent() {

return parent;

}

public void setParent(Node parent) {

this.parent = parent;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getIndex() {

return index;

}

public void setIndex(int index) {

this.index = index;

}

}

}

打印结果:

测试

测试1

测试2

测试专用

123456

test

123

工单

问题反馈309

问题反馈565

问题反馈54

问题反馈310

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值