一道递归笔试题

这种形式展现出来

思路:定义数据结构NodeTree将NodeTree放进List,然后遍历每个NodeTree,并将每个NodeTree的深度算出来,有多少深度前面就有多少-,然后打印。递归思想:NodeTree的parentId等于0的时候为最低深度直接返回,用for循环查找当前id的parentId在哪里找到打印一个“-”,然后循环递归。

import java.util.*;

public class TestRecursion {
    static List<NodeTree> nodeList = new ArrayList<>();

    public static void main(String[] args) {
        nodeList.add(new NodeTree(1, 0, "aa"));
        nodeList.add(new NodeTree(2, 1, "bb"));
        nodeList.add(new NodeTree(3, 1, "cc"));
        nodeList.add(new NodeTree(4, 3, "dd"));
        nodeList.add(new NodeTree(5, 4, "ee"));
        nodeList.add(new NodeTree(6, 5, "ff"));
        nodeList.add(new NodeTree(7, 0, "gg"));
        nodeList.add(new NodeTree(8, 7, "hh"));
        nodeList.add(new NodeTree(9, 7, "ii"));
        for (NodeTree nodeTree : nodeList) {
            print(nodeTree.getParentId(),nodeTree.getName());
            System.out.println("");
        }
    }

    static int x = 0;

    public static void print(int id, String name) {
        if (id == 0) {
            System.out.print("-" + name);
            return;
        }
        for (int i = 0; i < nodeList.size(); i++) {
            if (nodeList.get(i).getId() == id) {
                System.out.print("-");
                print(nodeList.get(i).getParentId(),name);
            }
        }
    }

}

class NodeTree {
    private int id;
    private int parentId;
    private String name;

    public NodeTree() {
    }

    public NodeTree(int id, int parentId, String name) {
        this.id = id;
        this.parentId = parentId;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getParentId() {
        return parentId;
    }

    public void setParentId(int parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值