java构建树,构建tree,组装树结构,通用算法,用到递归算法

算法1:利用数据结构,空间换取时间(组装时对初始数据顺序有要求)


import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class Mainin {

	static class Node {
		String code;
		String parentCode;

		List<Node> children;

		public Node() {
			super();
		}

		public Node(String code, String parentCode) {
			super();
			this.code = code;
			this.parentCode = parentCode;
		}

		public String getCode() {
			return code;
		}

		public void setCode(String code) {
			this.code = code;
		}

		public String getParentCode() {
			return parentCode;
		}

		public void setParentCode(String parentCode) {
			this.parentCode = parentCode;
		}

		public List<Node> getChildren() {
			return children;
		}

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

		public void addChildren(Node child) {
			if (children == null) {
				children = new ArrayList<Node>();
			}
			children.add(child);
		}
	}

	public static void main(String[] args) {
		List<Node> initList = initTreeData();
		Map<String, Node> root = new LinkedHashMap<String, Node>();
		for (Node item : initList) {
			Node parent = root.get(item.getParentCode());
			if (parent == null) {
				parent = new Node();
				root.put(item.getParentCode(), parent);
			}
			root.put(item.getCode(), item);
			parent.addChildren(item);
		}
		Node tree = root.get("0");
		System.out.println(GsonUtils.toJson(tree));
	}

	static List<Node> initTreeData() {
		List<Node> initList = new ArrayList<>();
		initList.add(new Node("001", "0"));
		initList.add(new Node("001001", "001"));
		initList.add(new Node("001002", "001"));
		initList.add(new Node("002", "0"));
		initList.add(new Node("002001", "002"));
		initList.add(new Node("002002", "002"));
		initList.add(new Node("002002001", "002002"));
		initList.add(new Node("002002002", "002002"));
		initList.add(new Node("003", "0"));
		initList.add(new Node("003001", "003"));
		initList.add(new Node("003002", "003"));
		initList.add(new Node("003002001", "003002"));
		initList.add(new Node("003002002", "003002"));
		initList.add(new Node("003002003", "003002"));
		initList.add(new Node("003002004", "003002"));
		initList.add(new Node("003002005", "003002"));
		initList.add(new Node("003002006", "003002"));
		initList.add(new Node("005", "0"));
		initList.add(new Node("005001", "005"));
		initList.add(new Node("005001002", "005001"));
		initList.add(new Node("005001002001", "005001002"));
		initList.add(new Node("005001002002", "005001002"));
		return initList;
	}

}

算法2:只有一个字段,需要自己算树结构 

请跟着main方法走,然后看代码注释。
package hesuangyan.com.testtree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Mainin {

    static class Node {
        // 节点对象,没有按照规范封装,直接.属性即可
        String code;

        List<Node> children = new ArrayList<Node>();
        Map<String, Node> childMap = new LinkedHashMap<String, Node>();

        Node() {
            this.code = "000";
        }

        Node(String code) {
            this.code = code;
        }

        @Override
        public String toString() {
            StringBuilder str = new StringBuilder();
            return printSelf(this, str);
        }

        public String printSelf(Node n, StringBuilder str) {//输出树的json结构
            List<Node> list = n.children;
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Node node = list.get(i);
                    int childeSize = node.children.size();
                    String mark = "";
                    if (childeSize != 0) {
                        mark = ":";
                    }
                    str.append("{code:" + node.code + mark);
                    printSelf(node, str);
                    str.append("}");
                    if (i + 1 != list.size()) {
                        str.append(",");
                    }
                }
            }
            return str.toString();
        }
    }

    public static void main(String[] args) {
        Node node = new Node();//
        initTreeData(node);// 构建树前的初始化平铺数据,模拟数据库查询出的数据

        Map<String, Node> rMap = new LinkedHashMap<String, Node>();// 临时组织数据map

        for (Node thisN : node.children) {
            turnToMap(rMap, thisN);// 将平铺的数据,解析到map中,构建一颗逻辑树
        }

        Node root = new Node();// 结果树
        turnToList(rMap, root);// 递归解析map树,并放入root这个根节点中
        System.out.println(root);
        // root既是结果树
    }

    static void turnToMap(Map<String, Node> rMap, Node n) {
        String key = null;
        List<String> keyList = new ArrayList<String>();
        for (int i = 0; i < n.code.length() / 3; i++) {// 组装code的父级结构
            key = n.code.substring(0, 3 + (i * 3));
            keyList.add(key);
        }

        String thisKey = null;
        Node tmpNode = null;
        Map<String, Node> tmpMap = rMap;
        for (int i = 0; i < keyList.size(); i++) {
            thisKey = keyList.get(i);
            tmpNode = tmpMap.get(thisKey);
            if (i + 1 == keyList.size()) {
                tmpMap.put(n.code, n);// 如果是末级节点,则放入该节点
            } else {
                tmpMap = tmpNode.childMap;// 如果不是末级节点,则将该节点赋值给临时变量
            }
        }
    }

    static void turnToList(Map<String, Node> rMap, Node rn) {
        Set<Entry<String, Node>> eSet = rMap.entrySet();
        Iterator<Entry<String, Node>> mIt = eSet.iterator();
        while (mIt.hasNext()) {
            Entry<String, Node> entry = mIt.next();
            Node node = entry.getValue();
            rn.children.add(node);
            turnToList(node.childMap, node);
        }
    }

    static void initTreeData(Node node) {
        node.children.add(new Node("001"));
        node.children.add(new Node("001001"));
        node.children.add(new Node("001002"));
        node.children.add(new Node("002"));
        node.children.add(new Node("002001"));
        node.children.add(new Node("002002"));
        node.children.add(new Node("002002001"));
        node.children.add(new Node("002002002"));
        node.children.add(new Node("003"));
        node.children.add(new Node("003001"));
        node.children.add(new Node("003002"));
        node.children.add(new Node("003002001"));
        node.children.add(new Node("003002002"));
        node.children.add(new Node("003002003"));
        node.children.add(new Node("003002004"));
        node.children.add(new Node("003002005"));
        node.children.add(new Node("003002006"));

        node.children.add(new Node("005"));
        node.children.add(new Node("005001"));
        node.children.add(new Node("005001002"));
        node.children.add(new Node("005001002001"));
        node.children.add(new Node("005001002002"));
    }

}

 

 

 

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 可以使用递归算法来实现列表转换为树结构。首先,需要定义一个树结构,比如用一个类来表示:class Node{ int data; Node left; Node right; }然后,可以定义一个函数,接受一个列表作为参数,并返回一棵:Node listToTree(List<Integer> list){ //创建根节点 Node root = new Node(list.get(0)); //遍历列表,构建二叉 for(int i = 1; i < list.size(); i++){ //当前节点的值 int val = list.get(i); //创建新节点 Node newNode = new Node(val); //从根节点开始插入 insertNode(root, newNode); } return root; }最后,可以定义一个函数用来插入新节点:void insertNode(Node parent, Node newNode){ //如果新节点的值小于父节点的值,插入到左子 if(newNode.data < parent.data){ //如果左子为空,直接插入 if(parent.left == null){ parent.left = newNode; }else{ //否则,递归插入 insertNode(parent.left, newNode); } //否则,插入到右子 }else{ //如果右子为空,直接插入 if(parent.right == null){ parent.right = newNode; }else{ //否则,递归插入 insertNode(parent.right, newNode); } } } ### 回答2: 要将列表转化为树结构,可以使用递归的方式来实现。 首先,定义一个节点类,包含一个value属性和一个children列表属性,用于表示每个节点的值和子节点列表。 然后,定义一个构建的方法,该方法接收一个列表参数和一个根节点参数。 在构建的方法中,我们首先创建一个空的节点对象,并将根节点参数的值赋给该节点的value属性。 然后,我们遍历列表参数,将每个元素与根节点比较,如果元素的父节点id与根节点的value属性相等,就说明该元素是根节点的子节点。 在这种情况下,我们创建一个新的节点对象,并将该元素的值赋给节点的value属性,然后将该节点加入到根节点的children列表中。 接下来,使用递归的方式,将这个新节点作为根节点,继续遍历列表参数,寻找其他的子节点。 递归的停止条件是找不到满足父节点id与根节点value相等的元素,或者列表参数为空。 最后,将构建好的树结构返回。 下面是一个使用Java实现的列表转化为树结构算法示例: ```java class TreeNode { int value; List<TreeNode> children; public TreeNode(int value) { this.value = value; this.children = new ArrayList<>(); } } public class ListToTreeConverter { public TreeNode convert(List<Element> elements, TreeNode root) { for (Element element : elements) { if (element.parentId == root.value) { TreeNode newNode = new TreeNode(element.value); root.children.add(newNode); convert(elements, newNode); } } return root; } public static void main(String[] args) { List<Element> elements = new ArrayList<>(); elements.add(new Element(1, 0)); elements.add(new Element(2, 1)); elements.add(new Element(3, 1)); elements.add(new Element(4, 2)); elements.add(new Element(5, 2)); elements.add(new Element(6, 3)); TreeNode root = new TreeNode(0); ListToTreeConverter converter = new ListToTreeConverter(); TreeNode tree = converter.convert(elements, root); // 遍历打印树结构 printTree(tree); } public static void printTree(TreeNode node) { System.out.println(node.value); for (TreeNode child : node.children) { printTree(child); } } } class Element { int value; int parentId; public Element(int value, int parentId) { this.value = value; this.parentId = parentId; } } ``` 这段代码中,我们定义了一个Element类来表示列表中的元素,其中包含value属性和parentId属性,分别表示节点的值和父节点的id。 我们通过构建一个元素列表,然后创建一个根节点,调用convert方法进行转化,最后通过printTree方法遍历打印树结构。 以上就是使用Java写一个列表转结构转化为树结构算法的示例。有很多种实现方式,具体实现取决于具体的需求和数据结构。 ### 回答3: 要将列表转化为树结构算法,我们可以使用Java编程语言来实现。下面是一个基本思路的示例代码,并说明了步骤: ```java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ListToTree { // 定义节点类 static class TreeNode { int id; String name; List<TreeNode> children; TreeNode(int id, String name) { this.id = id; this.name = name; children = new ArrayList<>(); } } public static void main(String[] args) { // 示例的列表数据 List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> node1 = new HashMap<>(); node1.put("id", 1); node1.put("name", "Node 1"); node1.put("parent_id", 0); list.add(node1); Map<String, Object> node2 = new HashMap<>(); node2.put("id", 2); node2.put("name", "Node 2"); node2.put("parent_id", 0); list.add(node2); Map<String, Object> node3 = new HashMap<>(); node3.put("id", 3); node3.put("name", "Node 3"); node3.put("parent_id", 1); list.add(node3); // 构建树结构 List<TreeNode> tree = buildTree(list); // 打印树结构 printTree(tree); } // 构建树结构的方法 private static List<TreeNode> buildTree(List<Map<String, Object>> list) { List<TreeNode> tree = new ArrayList<>(); Map<Integer, TreeNode> nodeMap = new HashMap<>(); // 先创建所有节点,存储到Map中 for (Map<String, Object> nodeData : list) { int id = (int) nodeData.get("id"); String name = (String) nodeData.get("name"); TreeNode node = new TreeNode(id, name); nodeMap.put(id, node); } // 根据列表中的parent_id,构建树结构 for (Map<String, Object> nodeData : list) { int id = (int) nodeData.get("id"); int parentId = (int) nodeData.get("parent_id"); TreeNode node = nodeMap.get(id); TreeNode parent = nodeMap.get(parentId); if (parent != null) { parent.children.add(node); } else { tree.add(node); // 根节点 } } return tree; } // 打印树结构的方法 private static void printTree(List<TreeNode> tree) { for (TreeNode node : tree) { printNode(node, 0); } } // 递归打印节点及其子节点 private static void printNode(TreeNode node, int depth) { for (int i = 0; i < depth; i++) { System.out.print("--"); // 按深度打印前缀符 } System.out.println(node.name); // 打印节点名称 for (TreeNode child : node.children) { printNode(child, depth + 1); // 递归打印子节点 } } } ``` 以上示例代码实现了一个将给定的列表数据转化为树结构算法。首先,我们通过创建`TreeNode`类来定义节点的数据结构,包括id、name和children字段。然后,我们使用一个方法`buildTree`根据给定的列表数据来构建树结构,并返回的根节点列表。在构建的过程中,我们先创建所有节点,并将它们存储在一个`Map`中,使用节点的id作为键。然后,根据列表中的parent_id来找到每个节点的父节点,并将当前节点添加到父节点的children列表中。最后,我们可以使用`printTree`方法来打印整个的结构,以及每个节点的名称。 请注意,上述示例代码仅为演示目的,实际应用中可能需要根据具体需求进行适当的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值