利用Stack构造树状列表

数据库中利用ParentId实现树状列表,如果查询出先根(根左右)遍历的列表,可以用本文介绍的方法构造出树结构。

List<OrganizationInfo> list= #查询出先根列表#

OrganizationTree tree= new OrganizationTree();
buildOrganTree(list,tree);

return tree;

其中OrganizationInfo为结点类型,其中有指示父节点的属性。

 需要构建的树:

public class OrganizationTree implements Serializable{
    
    private OrganizationInfo  node;
    private List<OrganizationTree> childNodes;
}

 实现过程:

private void buildOrganTree(List<OrganizationInfo> list,OrganizationTree tree)
    {
        Stack<OrganizationTree> st = new Stack<OrganizationTree>();
        if(list.size()<=0) return;
        OrganizationInfo curNode = list.get(0);
        tree.setNode(curNode);
        
        OrganizationTree pNode = tree;
        OrganizationTree preNode = tree;
        for(int i=1;i<list.size();i++){
            OrganizationTree snode = new OrganizationTree();
            snode.setNode(list.get(i));
            if( list.get(i).getParentId().equals(pNode.getNode().getOrganizationId()) ){
                if(pNode.getChildNodes()==null){
                    List<OrganizationTree> child = new ArrayList<OrganizationTree>();
                    child.add(snode);
                    pNode.setChildNodes(child);                    
                }
                else{
                    pNode.getChildNodes().add(snode);
                }
            }
            else{
                if( list.get(i).getParentId().equals(list.get(i-1).getOrganizationId()))
                {
                    st.push(pNode);
                    pNode = preNode;
                    if(pNode.getChildNodes()==null){
                        List<OrganizationTree> child = new ArrayList<OrganizationTree>();
                        child.add(snode);
                        pNode.setChildNodes(child);                    
                    }
                    else{
                        pNode.getChildNodes().add(snode);
                    }
                }
                else{
                    do{
                        pNode =st.pop();
                    }while( !list.get(i).getParentId().equals(pNode.getNode().getOrganizationId()) );
                    pNode.getChildNodes().add(snode);                    
                }
            }
            preNode =snode;
        }
    }

 

转载于:https://www.cnblogs.com/pphusoft/p/5959603.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值