如何用Java实现树形结构?
[java] view plain copy
package com.tree.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args){
showTree();
}
public static void showTree(){
Connection conn=null;
ResultSet rs = null;
Statement stmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost/tree?user=root&password=root");
/*stmt=conn.createStatement();
rs=stmt.executeQuery("select * from country where pid=0");
while(rs.next()){
System.out.println(rs.getString("actile"));*/
tree(conn,0,0);
// }
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void tree(Connection conn,int id,int level){
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
String sql = "select * from country where pid = " + id;
rs = stmt.executeQuery(sql);
while(rs.next()) {
StringBuffer strPre = new StringBuffer("");
for(int i=0; i<level; i++) {
strPre.append(" ");
}
System.out.println(strPre + rs.getString("actile"));
if(rs.getInt("is_leaf") != 0)
tree(conn, rs.getInt("id"), level + 1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
数据库
[sql] view plain copy
create database tree;
use tree;
create table country
(
id int primary key auto_increment,
pid int,
actile varchar(40),
is_leaf int
);
insert into country values(1,0, '中国',1);
insert into country values(2,1,'北京',0);
insert into country values(3,0,'美国',1);
insert into country values(4,3,'纽约',0);
insert into country values(5,1,'浙江',1);
insert into country values(6,5,'杭州',1);
insert into country values(7,6,'滨江',0);