关于二叉树,请高人解答
Create Table
CREATE TABLE `basetree` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(100) DEFAULT NULL COMMENT '名称',
`parentId` int(255) DEFAULT '-1' COMMENT '父ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8
实际上是一个自引用
dao层代码:
public List<BaseTree> getBaseTree(BaseTree baseTree) throws Exception {
List<BaseTree> baseTreesList = sqlSession.selectList("constants.selectBaseTree", baseTree.getParentId());
return baseTreesList;
}
配置:
<select id="selectBaseTree" resultType="BaseTree" parameterType="int">
SELECT id, NAME, parentId FROM ms.basetree
where parentId = #{parentId}
</select>
bean:
public class BaseTree extends BaseBean {
private Integer parentId;
private List<BaseTree> baseTree;
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public List<BaseTree> getBaseTree() {
return baseTree;
}
public void setBaseTree(List<BaseTree> baseTree) {
this.baseTree = baseTree;
}
}
Service:
怎么写才能将二叉树保存到list中?展示层如何展示?
Java?二叉树
------解决方案--------------------很多js插件能实现树型结构展示 比如ztree
------解决方案--------------------
public String recursion(String id){
StringBuilder builder=new StringBuilder();
List<Map> list=subTreeList(id);
if(list.size()>0){
for (int i = 0; i < list.size(); i++) {
builder.append("<item text=\""+list.get(i).get("name")+"\" id=\""+list.get(i).get("id")+"\" open=\"1\">");
builder.append(recursion(list.get(i).get("id").toString()));
builder.append("</item>");
}
}
return builder.toString();
}
public String assemTree(String root){
List<Map> list=getTreeList(root);
StringBuilder builder=new StringBuilder();
builder.append("<?xml version='1.0' encoding='UTF-8'?>");
builder.append("<tree id=\"0\">");
builder.append("<item text=\""+list.get(0).get("name")+"\" id=\""+list.get(0).get("id")+"\" open=\"1\" call=\"1\" select=\"1\">");
builder.append(recursion(root));
builder.append("</item>");
builder.append("</tree>");
return builder.toString();
}
递归,之前的demo你可以参考下
------解决方案--------------------public List<Map> subTreeList(String parent){
String sql="select * from fl_perm where parent in (?) order by orderid asc";
List<Map> lm=jdbcTemplate.queryForList(sql,new Object[]{parent});
return lm;
}
------解决方案--------------------用Key-value的形式存在map里就可以了啊。。。