java遍历树获取所有路径

/**
 * 遍历获取链路路径,使用深度优先
 */

public class IteratorPathUtil {
    Map<String, List> pathMap=new HashMap();//记录全部从根节点到叶子结点的路径
    public Map<String, List> getPathMap()//返回路径map
    {
        return pathMap;
    }
    public void iteratorNode(PathVo n, Stack<PathVo> pathstack)
    {
        pathstack.push(n);//入栈
        List<PathVo> childlist=n.getPathVoList();
        if(childlist==null)//没有孩子 说明是叶子结点
        {
            List lst=new ArrayList();
            Iterator<PathVo> stackIt=pathstack.iterator();
            while(stackIt.hasNext())
            {
                lst.add(stackIt.next().getZDeviceId());

            }
            pathMap.put(n.getZDeviceId(), lst);//保存路径信息
        }
        else
        {
            Iterator it=childlist.iterator();
            while(it.hasNext())
            {
                PathVo child=(PathVo)it.next();
                iteratorNode(child,pathstack);//深度优先 进入递归
                pathstack.pop();//回溯时候出栈
            }

        }

    }

}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容