Home Java javaTutorial Implementing infinite levels of tree structure methods in java and js (similar to recursion)

Implementing infinite levels of tree structure methods in java and js (similar to recursion)

Jan 10, 2017 pm 12:52 PM

In js:

var zNodes=[
{id:0,pId:-1,name:"Aaaa"},
  {id:1,pId:0,name:"A"},
  {id:11,pId:1,name:"A1"},
  {id:12,pId:1,name:"A2"},
  {id:13,pId:1,name:"A3"},
  {id:2,pId:0,name:"B"},
  {id:21,pId:2,name:"B1"},
  {id:22,pId:2,name:"B2"},
  {id:23,pId:2,name:"B3"},
  {id:3,pId:0,name:"C"},
  {id:31,pId:3,name:"C1"},
  {id:32,pId:3,name:"C2"},
  {id:33,pId:3,name:"C3"},
  {id:34,pId:31,name:"x"},
  {id:35,pId:31,name:"y"}, 
  {id:36,pId:31,name:"z"},
  {id:37,pId:36,name:"z1123"} ,
  {id:38,pId:37,name:"z123123123"}  
];
function treeMenu(a){
  this.tree=a||[];
  this.groups={};
};
treeMenu.prototype={
  init:function(pid){
    this.group();
    return this.getDom(this.groups[pid]);
  },
  group:function(){
    for(var i=0;i<this.tree.length;i++){
      if(this.groups[this.tree[i].pId]){
        this.groups[this.tree[i].pId].push(this.tree[i]);
      }else{
        this.groups[this.tree[i].pId]=[];
        this.groups[this.tree[i].pId].push(this.tree[i]);
      }
    }
  },
  getDom:function(a){
    if(!a){return &#39;&#39;}
    var html=&#39;\n<ul >\n&#39;;
    for(var i=0;i<a.length;i++){
      html+=&#39;<li><a href="#">&#39;+a[i].name+&#39;</a>&#39;;
      html+=this.getDom(this.groups[a[i].id]);
      html+=&#39;</li>\n&#39;;
    };
    html+=&#39;</ul>\n&#39;;
    return html;
  }
};
var html=new treeMenu(zNodes).init(0);
alert(html);
Copy after login

java:

package test;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Collections;
 
/**
 * 多叉树类
*/
public class MultipleTree {
 public static void main(String[] args) {
 // 读取层次数据结果集列表 
 List dataList = VirtualDataGenerator.getVirtualResult(); 
  
 // 节点列表(散列表,用于临时存储节点对象)
 HashMap nodeList = new HashMap();
 // 根节点
 Node root = null;
 // 根据结果集构造节点列表(存入散列表)
 for (Iterator it = dataList.iterator(); it.hasNext();) {
  Map dataRecord = (Map) it.next();
  Node node = new Node();
  node.id = (String) dataRecord.get("id");
  node.text = (String) dataRecord.get("text");
  node.parentId = (String) dataRecord.get("parentId");
  nodeList.put(node.id, node);
 }
 // 构造无序的多叉树
 Set entrySet = nodeList.entrySet();
 for (Iterator it = entrySet.iterator(); it.hasNext();) {
  Node node = (Node) ((Map.Entry) it.next()).getValue();
  if (node.parentId == null || node.parentId.equals("")) {
  root = node;
  } else {
  ((Node) nodeList.get(node.parentId)).addChild(node);
  }
 }
 // 输出无序的树形菜单的JSON字符串
 System.out.println(root.toString());  
 // 对多叉树进行横向排序
 root.sortChildren();
 // 输出有序的树形菜单的JSON字符串
 System.out.println(root.toString()); 
  
 // 程序输出结果如下(无序的树形菜单)(格式化后的结果): 
 // {
 //  id : &#39;100000&#39;, 
 //  text : &#39;廊坊银行总行&#39;, 
 //  children : [
 //   {
 //   id : &#39;110000&#39;, 
 //   text : &#39;廊坊分行&#39;, 
 //   children : [
 //    {
 //    id : &#39;113000&#39;, 
 //    text : &#39;廊坊银行开发区支行&#39;, 
 //    leaf : true
 //    },
 //    {
 //    id : &#39;111000&#39;, 
 //    text : &#39;廊坊银行金光道支行&#39;, 
 //    leaf : true
 //    },
 //    {
 //    id : &#39;112000&#39;, 
 //    text : &#39;廊坊银行解放道支行&#39;, 
 //    children : [
 //     {
 //     id : &#39;112200&#39;, 
 //     text : &#39;廊坊银行三大街支行&#39;, 
 //     leaf : true
 //     },
 //     {
 //     id : &#39;112100&#39;, 
 //     text : &#39;廊坊银行广阳道支行&#39;, 
 //     leaf : true
 //     }
 //    ]
 //    }
 //   ]
 //   }
 //  ]
 // }
 
 // 程序输出结果如下(有序的树形菜单)(格式化后的结果):
 // {
 //  id : &#39;100000&#39;, 
 //  text : &#39;廊坊银行总行&#39;, 
 //  children : [
 //   {
 //   id : &#39;110000&#39;, 
 //   text : &#39;廊坊分行&#39;, 
 //   children : [
 //    {
 //    id : &#39;111000&#39;, 
 //    text : &#39;廊坊银行金光道支行&#39;, 
 //    leaf : true
 //    },
 //    {
 //    id : &#39;112000&#39;, 
 //    text : &#39;廊坊银行解放道支行&#39;, 
 //    children : [
 //     {
 //     id : &#39;112100&#39;, 
 //     text : &#39;廊坊银行广阳道支行&#39;, 
 //     leaf : true
 //     },
 //     {
 //     id : &#39;112200&#39;, 
 //     text : &#39;廊坊银行三大街支行&#39;, 
 //     leaf : true
 //     }
 //    ]
 //    },
 //    {
 //    id : &#39;113000&#39;, 
 //    text : &#39;廊坊银行开发区支行&#39;, 
 //    leaf : true
 //    }
 //   ]
 //   }
 //  ]
 // } 
  
 }
   
}
 
 
/**
* 节点类
*/
class Node {
 /**
 * 节点编号
 */
 public String id;
 /**
 * 节点内容
 */
 public String text;
 /**
 * 父节点编号
 */
 public String parentId;
 /**
 * 孩子节点列表
 */
 private Children children = new Children();
  
 // 先序遍历,拼接JSON字符串
 public String toString() { 
 String result = "{"
  + "id : &#39;" + id + "&#39;"
  + ", text : &#39;" + text + "&#39;";
  
 if (children != null && children.getSize() != 0) {
  result += ", children : " + children.toString();
 } else {
  result += ", leaf : true";
 }
   
 return result + "}";
 }
  
 // 兄弟节点横向排序
 public void sortChildren() {
 if (children != null && children.getSize() != 0) {
  children.sortChildren();
 }
 }
  
 // 添加孩子节点
 public void addChild(Node node) {
 this.children.addChild(node);
 }
}
 
/**
* 孩子列表类
*/
class Children {
 private List list = new ArrayList();
  
 public int getSize() {
 return list.size();
 }
  
 public void addChild(Node node) {
 list.add(node);
 }
  
 // 拼接孩子节点的JSON字符串
 public String toString() {
 String result = "["; 
 for (Iterator it = list.iterator(); it.hasNext();) {
  result += ((Node) it.next()).toString();
  result += ",";
 }
 result = result.substring(0, result.length() - 1);
 result += "]";
 return result;
 }
  
 // 孩子节点排序
 public void sortChildren() {
 // 对本层节点进行排序
 // 可根据不同的排序属性,传入不同的比较器,这里传入ID比较器
 Collections.sort(list, new NodeIDComparator());
 // 对每个节点的下一层节点进行排序
 for (Iterator it = list.iterator(); it.hasNext();) {
  ((Node) it.next()).sortChildren();
 }
 }
}
 
/**
 * 节点比较器
 */
class NodeIDComparator implements Comparator {
 // 按照节点编号比较
 public int compare(Object o1, Object o2) {
 int j1 = Integer.parseInt(((Node)o1).id);
   int j2 = Integer.parseInt(((Node)o2).id);
   return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));
 } 
}
 
/**
 * 构造虚拟的层次数据
 */
class VirtualDataGenerator {
 // 构造无序的结果集列表,实际应用中,该数据应该从数据库中查询获得;
 public static List getVirtualResult() {  
 List dataList = new ArrayList();
  
 HashMap dataRecord1 = new HashMap();
 dataRecord1.put("id", "112000");
 dataRecord1.put("text", "廊坊银行解放道支行");
 dataRecord1.put("parentId", "110000");
  
 HashMap dataRecord2 = new HashMap();
 dataRecord2.put("id", "112200");
 dataRecord2.put("text", "廊坊银行三大街支行");
 dataRecord2.put("parentId", "112000");
  
 HashMap dataRecord3 = new HashMap();
 dataRecord3.put("id", "112100");
 dataRecord3.put("text", "廊坊银行广阳道支行");
 dataRecord3.put("parentId", "112000");
    
 HashMap dataRecord4 = new HashMap();
 dataRecord4.put("id", "113000");
 dataRecord4.put("text", "廊坊银行开发区支行");
 dataRecord4.put("parentId", "110000");
    
 HashMap dataRecord5 = new HashMap();
 dataRecord5.put("id", "100000");
 dataRecord5.put("text", "廊坊银行总行");
 dataRecord5.put("parentId", "");
  
 HashMap dataRecord6 = new HashMap();
 dataRecord6.put("id", "110000");
 dataRecord6.put("text", "廊坊分行");
 dataRecord6.put("parentId", "100000");
  
 HashMap dataRecord7 = new HashMap();
 dataRecord7.put("id", "111000");
 dataRecord7.put("text", "廊坊银行金光道支行");
 dataRecord7.put("parentId", "110000"); 
   
 dataList.add(dataRecord1);
 dataList.add(dataRecord2);
 dataList.add(dataRecord3);
 dataList.add(dataRecord4);
 dataList.add(dataRecord5);
 dataList.add(dataRecord6);
 dataList.add(dataRecord7);
  
 return dataList;
 } 
}
Copy after login

The above article on how to implement infinite levels of tree structure in java and js (similar to recursion) is all the content shared by the editor. , I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.

For more related articles on implementing infinite levels of tree structure methods (similar to recursion) in java and js, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? Apr 19, 2025 pm 07:15 PM

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? Apr 19, 2025 pm 01:51 PM

Discussing the hierarchical architecture in back-end development. In back-end development, hierarchical architecture is a common design pattern, usually including controller, service and dao three layers...

See all articles