---
title: "数据库递归算法jav"
author: "Narnia08"
date: "2009-03-21T20:19:06Z"
tags: ["CMS", "数据结构", "算法"]
slug: "jav"
draft: false
lastmod: "2009-03-21T20:19:06Z"
id: 352860
url: "https://narnia08.iteye.com/blog/352860"
---

表结构

字段1     字段2
1             0
2             1
3             1
4             2
5             2
6             4

//根据父ID查询子ID
public static ArrayList getAllSubCateIdFromPARENTCATEID(String parentid) throws Exception {
 DataBase db = null;
 db = DataBaseFactory.getDataBase(0);
 PreStatement stmt = null;
 RecordSet rst = null;
 
 ArrayList list = new ArrayList();
 
 stmt = db.setStatement("SELECT CATE_ID FROM CMS_CATEGORY WHERE CATE_PARENTCATEID = ?");
 stmt.setString(1, parentid);
 
 rst = db.executeQuery();

 while(rst.next()){
  list.add(rst.getString("CATE_ID"));//将子结点添加模拟树
 }
 db.close();
 return list;

}

//获得当前栏目ID下的所有子栏目
 public static StringBuffer getAllSubCateID(String parentid) throws Exception {
  //思路：表(实际树)---模拟树---模拟堆栈---输出队列
  ArrayList list = new ArrayList();//模拟堆栈
  ArrayList list2 = new ArrayList();//模拟树--只记录节点下的子结点(不记录所有树形结构)

  StringBuffer str = new StringBuffer();
  String tempParentId = "";
  tempParentId = parentid;
  
  list.add(parentid);//把第一个结点压入堆栈

  list2 = getAllSubCateIdFromPARENTCATEID(tempParentId);//把第一个结点的子结点加到树上
  
  str.append("'"+tempParentId+"',");//当第一个节点放入
  
  if(list.isEmpty()){//当树 第一个节点没有子节点时，什么都不做
  }else{   
   while (!list.isEmpty()) {//当树 第一个节点有子节点时，开始循环获得子结点
    //System.out.println("++ "+list.size());
    //System.out.println("-- "+list2.size());
    if (list2.isEmpty()) {// 叶子节点 
     //System.out.println("叶子节点");
     list.remove(list.size()-1);//删除堆栈顶端节点
    } else {     //非叶子节点
     //System.out.println("非叶子节点");
     
     int step = 0;
     
     while (!list2.isEmpty()) {
      list.add(list2.get(list2.size()-1));// 把 非叶子节点 压入 堆栈
      
      str.append("'"+(String)list2.get(list2.size()-1)+"',");//把当前节点 压入 输出队列
      
      list2.remove(list2.size()-1);//删除 非叶子节点
      
      ++step;
      
     }
     //把下一层的所有子结点压入堆栈
     for(int u=1;u<=step;u++){
      list2.addAll(getAllSubSiteIdFromPARENTCATEID((String)list.get(list.size()-u)));//根据堆栈顶端节点查询子结点放入模拟树中
     }
    }
    
   }
  }
  
  str = new StringBuffer(str.substring(0,str.lastIndexOf(",")));

  return str;
 }修改了点错误，这个算法有点慢……听说二叉树排序会快点……有机会再改。
