반복 생성 논리 트리

3200 단어 Java 기반
트리 노드 설계:
package com.zhjg.tree;

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

public class TreeNode {

	private String id;
	private String name;
	private String desc;
	private String pid;
	private List children;
	
	
	public TreeNode() {
		super();
	}
	
	public TreeNode(String id, String name, String desc, String pid) {
		super();
		this.id = id;
		this.name = name;
		this.desc = desc;
		this.pid = pid;
		this.children = new ArrayList();
	}


	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDesc() {
		return desc;
	}
	public void setDesc(String desc) {
		this.desc = desc;
	}
	public String getPid() {
		return pid;
	}
	public void setPid(String pid) {
		this.pid = pid;
	}

	public List getChildren() {
		return children;
	}

	public void setChildren(List children) {
		this.children = children;
	}
	
}

트리 구조의 클래스 생성(테스트에 fastjson의 종속성을 추가해야 함):
package com.zhjg.tree;

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

import com.alibaba.fastjson.JSON;

/**
 *  
 *  
 * @author 327084
 *
 */
public class RecursiveTree {
	
	/**
	 *  
	 * @param nodes
	 * @return
	 */
	public static String switchNodeListToTree(List nodes){
		TreeNode root = getRoot(nodes);
		root = recursive(root, nodes);
		return JSON.toJSONString(root, true);
	}

	/**
	 *  
	 * @param node
	 * @param nodes
	 * @return
	 */
	public static TreeNode recursive(TreeNode node, List nodes){
		
		for (TreeNode treeNode : nodes) {
			if(treeNode.getPid().equals(node.getId())){// 
				node.getChildren().add(treeNode);
				recursive(treeNode, nodes);
			}
		}
		
		return node;
	}
	
	/**
	 *  
	 * @param nodes
	 * @return
	 */
	public static TreeNode getRoot(List nodes){
		TreeNode root = null;
		if(nodes != null && nodes.size() > 0){
			for (TreeNode treeNode : nodes) {
				if("".equals(treeNode.getPid())){
					root = treeNode;
					break;
				}
			}
		}
		return root;
	}
	
	/**
	 *  
	 * @param args
	 */
	public static void main(String[] args) {
		TreeNode root = new TreeNode("1", " ", " ", "");
		TreeNode node1 = new TreeNode("11", " ", " ", "1");
		TreeNode node2 = new TreeNode("12", " ", " ", "1");
		TreeNode node3 = new TreeNode("13", " ", " ", "1");
		TreeNode node4 = new TreeNode("131", " ", " ", "13");
		TreeNode node5 = new TreeNode("1311", " ", " ", "131");
		TreeNode node6 = new TreeNode("111", " ", " ", "11");
		List nodes = new ArrayList();
		nodes.add(root);
		nodes.add(node1);
		nodes.add(node2);
		nodes.add(node3);
		nodes.add(node4);
		nodes.add(node5);
		nodes.add(node6);
		System.out.println(switchNodeListToTree(nodes));
	}
}

좋은 웹페이지 즐겨찾기