JAVA 树状结构数据_根到每个最底层叶子的路径

数据结构:

public class node {
    private String text;
    private List<node>childList;
    
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
    public List<node> getChildList() {
        return childList;
    }
    public void setChildList(List<node> childList) {
        this.childList = childList;
    }
   }

 数据准备:

 测试代码 

public class IteratorNodeTool {
    private void print(List lst)//打印出路径
    {
        Iterator it = lst.iterator();
        while (it.hasNext()) {
            node n = (node) it.next();
            System.out.print(n.getText() + "-");
        }
        System.out.println();
    }
    public void iteratorNode(node n, Stack<node> pathstack) {
        pathstack.push(n);//入栈
        List childlist = n.getChildList();
        if (childlist == null)//没有孩子 说明是叶子结点
        {
            List lst = new ArrayList();
            Iterator stackIt = pathstack.iterator();
            while (stackIt.hasNext()) {
                lst.add(stackIt.next());
            }
            print(lst);//打印路径
        } else {
            Iterator it = childlist.iterator();
            while (it.hasNext()) {
                node child = (node) it.next();
                iteratorNode(child, pathstack);//深度优先 进入递归
                pathstack.pop();//回溯时候出栈
            }
        }
    }
    public static void main(String[] args) {
        List<node> roots = node.getInitNode();
        IteratorNodeTool tool = new IteratorNodeTool();
        for (node n : roots) {
            Stack<node> pathstack = new Stack();
            tool.iteratorNode(n, pathstack);
        }
    }

}

输出结果: 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值