java递归创建树

 

package com.kd.createimage;

import java.util.List;
/**
 * 节点类
 * @author lizc
 *
 */
public class Node {
    private String parent;//父节点名字
    private String nodeName;//当前节点名字
    private List<Node> childrenList;//子节点集合
    
    private int width;//节点宽度
    private int height;//节点长度
    private int left;//节点左位置
    private int right;//节点右位置
    
    public float getWidth() {
        return width;
    }
    
    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getLeft() {
        return left;
    }

    public void setLeft(int left) {
        this.left = left;
    }

    public int getRight() {
        return right;
    }

    public void setRight(int right) {
        this.right = right;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public String getParent() {
        return parent;
    }
    public void setParent(String parent) {
        this.parent = parent;
    }
    public String getNodeName() {
        return nodeName;
    }
    public void setNodeName(String nodeName) {
        this.nodeName = nodeName;
    }
    public List<Node> getChildrenList() {
        return childrenList;
    }
    public void setChildrenList(List<Node> childrenList) {
        this.childrenList = childrenList;
    }
    
}
 

创建树形结构类

package com.kd.createimage;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * 递归构建树 工具类
 * @author TR
 *
 */
public class TreeManager {
    private static List<Node> nodeList = null;//所有节点的集合
    private static Node treeNode;//根节点
    /**
     * 构建树
     * @param currentNode 当前节点对象
     * @param nodeList 所有节点的集合
     * @return
     */
    public static Node buildTree(Node currentNode,List<Node> nodeList){
        if(nodeList == null){
            return null;
        }
        if(nodeList.size() == 0){
            return treeNode;
        }
        
        if(treeNode == null){
            treeNode = new Node();
            treeNode.setNodeName("root");
        }
        //子节点集合初始化
        ArrayList<Node> chilldrenNodes = new ArrayList<Node>();
        Iterator<Node> it = nodeList.iterator();
        //对所有节点集合进行遍历
        if(currentNode == null){//currentNode 是null 说明是第一次调用 获取所有的第一层节点
            currentNode = treeNode;
        }
        while(it.hasNext()){
            Node node = it.next();//获取每一个节点
            if(node.getParent() == null){
                chilldrenNodes.add(node);//向子节点中添加元素
                it.remove();//将查找到的这个子节点从 node列表中删除
            }
            else{
                if(node.getParent().equals(currentNode.getNodeName())){
                    chilldrenNodes.add(node);//向子节点中添加元素
                    it.remove();//将查找到的这个子节点从 node列表中删除
                }
            }
        }
        currentNode.setChildrenList(chilldrenNodes);
        //对每一个子节点 进行递归调用 查找其子节点
        for(int i = 0;i < chilldrenNodes.size();i++){
            Node cNode = chilldrenNodes.get(i);
            //递归调用
            buildTree(cNode,nodeList);
        }
        return treeNode;
    }
    /**
     * 添加一个新节点
     * @param nodeName 节点名称
     * @param parent 父节点
     */
    public static void addNode(String nodeName,String parent){
        if(nodeList == null){
            nodeList = new ArrayList<Node>();
        }
        Node node = new Node();
        node.setNodeName(nodeName);
        node.setParent(parent);
        nodeList.add(node);
    }
    public static void main(String[] args){
        /*addNode("d1",null);
        addNode("d2","d1");
        addNode("d3","d2");
        addNode("d4","d3");
        addNode("d5","d4");
        addNode("d6","d5");
        addNode("d7","d6");
        addNode("d8","d7");
        addNode("d9","d4");
        addNode("d10","d6");
        addNode("d11","d10");
        addNode("d12","d11");
        addNode("d13","d12");
        addNode("d14","d12");
        addNode("d15","d14");*/
        addNode("d1",null);
        addNode("d2",null);
        addNode("d3","d1");
        addNode("d4","d2");
        addNode("d5","d2");
        addNode("d6","d5");
        buildTree(null,nodeList);
    }
}    
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
无限级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、付费专栏及课程。

余额充值