递归

同样是递归,一个是遍历到最后一个才开始获取名称一个一个返回,另一个是一开始就获取名称,遍历到最后一个直接返回

@Test
    public void test15() {
        
        LcxTest t = new LcxTest();
        
        Organization o1 = new Organization();
        o1.setName("123");
        
        Organization o2 = new Organization();
        o2.setName("456");
        o2.setParentOrgz(o1);
        
        Organization o3 = new Organization();
        o3.setName("789");
        o3.setParentOrgz(o2);
        
        System.out.println(t.findFullOrgzName(o3));
        
        Organization o4 = new Organization();
        o4.setName("101112");
        o4.setParentOrgz(o3);
        
        System.out.println(t.findFullOrgzName(o4));
        
    }
    
    public String findFullOrgzName(Organization curr) {
        if (curr == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        addParentName(curr.getParentOrgz(), sb);
        sb.append(curr.getName());
        return sb.toString();
    }
    private void addParentName(Organization orgz, StringBuilder sb) {
        if (orgz.getParentOrgz() != null) {
            addParentName(orgz.getParentOrgz(), sb);
        }
        sb.append(orgz.getName() + " • ");
    }
    
    public String findFullOrgzName2(Organization curr) {
        if (curr == null) {
            return "";
        }
        return addParentName2(curr.getParentOrgz(), curr.getName());
    }
    private String addParentName2(Organization orgz, String childs) {
        childs = orgz.getName() + " • " + childs;
        if (orgz.getParentOrgz() != null) {
            return addParentName2(orgz.getParentOrgz(), childs);
        }
        return childs;
    }

你们觉得哪一个好呢?欢迎留言。

还有下面这种,while循环方式

    public String areaFullName(DeviceArea deviceArea) {
        if (deviceArea == null) {
            return "";
        }

        String name = deviceArea.getName();
        if (deviceArea.getParentArea() == null) {
            return name;
        }

        while (deviceArea.getParentArea() != null) {
            name = deviceArea.getParentArea().getName() + " • " + name;
            deviceArea = deviceArea.getParentArea();
        }

        return name;
    }

 

posted @ 2020-12-07 11:00  1156740846  阅读(65)  评论(0编辑  收藏  举报