如何用Java实现树形结构?

 我来答
馃挵澶氭潨
2018-04-10 · TA获得超过1万个赞
知道小有建树答主
回答量:443
采纳率:0%
帮助的人:13.7万
展开全部

[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);

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式