java、js中实现无限层级的树形结构(类似递归)

本文通过JavaScript展示了如何创建并操作多叉树,并对其进行了横向排序,详细介绍了树的结构、节点类、子列表类及其相关算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 ''}
        var html='\n<ul >\n';
        for(var i=0;i<a.length;i++){
            html+='<li><a href="#">'+a[i].name+'</a>';
            html+=this.getDom(this.groups[a[i].id]);
            html+='</li>\n';
        };
        html+='</ul>\n';
        return html;
    }
};
var html=new treeMenu(zNodes).init(0);
alert(html);

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 : '100000', 
  //   text : '廊坊银行总行', 
  //   children : [
  //     {
  //     id : '110000', 
  //     text : '廊坊分行', 
  //     children : [
  //       {
  //       id : '113000', 
  //       text : '廊坊银行开发区支行', 
  //       leaf : true
  //       },
  //       {
  //       id : '111000', 
  //       text : '廊坊银行金光道支行', 
  //       leaf : true
  //       },
  //       {
  //       id : '112000', 
  //       text : '廊坊银行解放道支行', 
  //       children : [
  //         {
  //         id : '112200', 
  //         text : '廊坊银行三大街支行', 
  //         leaf : true
  //         },
  //         {
  //         id : '112100', 
  //         text : '廊坊银行广阳道支行', 
  //         leaf : true
  //         }
  //       ]
  //       }
  //     ]
  //     }
  //   ]
  //  }

  // 程序输出结果如下(有序的树形菜单)(格式化后的结果):
  //  {
  //   id : '100000', 
  //   text : '廊坊银行总行', 
  //   children : [
  //     {
  //     id : '110000', 
  //     text : '廊坊分行', 
  //     children : [
  //       {
  //       id : '111000', 
  //       text : '廊坊银行金光道支行', 
  //       leaf : true
  //       },
  //       {
  //       id : '112000', 
  //       text : '廊坊银行解放道支行', 
  //       children : [
  //         {
  //         id : '112100', 
  //         text : '廊坊银行广阳道支行', 
  //         leaf : true
  //         },
  //         {
  //         id : '112200', 
  //         text : '廊坊银行三大街支行', 
  //         leaf : true
  //         }
  //       ]
  //       },
  //       {
  //       id : '113000', 
  //       text : '廊坊银行开发区支行', 
  //       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 : '" + id + "'"
   + ", text : '" + text + "'";
  
  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;
 } 
}

 

转载地址: http://www.iteye.com/topic/1119961

无限级树(Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的树,递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值