树状结构中获取根节点到目标节点链路上的所有节点id

一个经典的java递归

树状结构中,获取根节点到目标节点链路上的所有节点id,看代码


    /**
     * 发现,即加入,并返回
     *
     * @param result  结果
     * @param resList 遍历对象
     * @param id      比较对象
     * @author: leiming5
     */
    private void getTargetList(List<Integer> result, List<AcResView> resList, Integer id) {
    
    

        for (AcResView resView : resList) {
    
    


            //  发现,立即返回
            if (resView.getId().equals(id)) {
    
    
                result.add(id);
                return;
            }

            // 发现,子类包含,也立即返回;
            if (isContinue(resView.getChildren(), id)) {
    
    

                getTargetList(result, resView.getChildren(), id);
                return;
            }
        }
    }

    /**
     * 判断子类是否包含
     *
     * @param resList 子类,
     * @param id      对比对象
     * @return 判断结果
     * @author: leiming5
     */
    private Boolean isContinue(List<AcResView> resList, Integer id) {
    
    

        Boolean res = false;
        for (AcResView resView : resList) {
    
    

            // 发现,也立即返回
            if (resView.getId().equals(id)) {
    
    
                return true;
            }

            // 没有发现,继续遍历他的子类
            res = isContinue(resView.getChildren(), id);

            // 如果孙子节点有,也立即返回;
            if (res) {
    
    
                return true;
            }
        }

        return false;
    }

猜你喜欢

转载自blog.csdn.net/leinminna/article/details/109681185